Chris
Chris

Reputation: 737

Binding function to Backbone Collection reset

Really basic question, but I can't seem to figure out why I am unable to bind a method to the reset event on a Collection.

HealthcheckList = Backbone.Collection.extend({

    model: Healthcheck,
    url: "/corsettiServices/rest/healthcheck/sort",

    initialize: function() {
        _.bindAll(this, "fetchSuccess", "addAll");
        console.log("Initializing view");
        this.on('reset', addAll);
        this.fetch({data: {type:'all'}, processData:true, success: this.fetchSuccess, reset: true});
    },

    addAll: function(m, options) {
        alert("adding");
    },

    fetchSuccess: function(m, response) {
        alert("success");
        console.log(m);
        m.each(function(h) {
            if (h.get("start")!=null) {
                $('#statusTable > tbody:last').append('<tr><td>' + h.get("start") + '</td><td>' + h.get("type") + '</td><td>' + h.get("status") + '</td></tr>');
            }
        })
    }
})

This throws an error: Uncaught ReferenceError: addAll is not defined. Removing the binding to the 'reset' event makes the data fetch and the code work, but I wanted to do more processing every time the collection was reset. What am I missing on how functions are supposed to be defined within a Backbone Collection?

Upvotes: 1

Views: 106

Answers (1)

Adam Lockhart
Adam Lockhart

Reputation: 1195

this.on("reset", this.addAll);

You want to be careful about scope. The initialize function will get bound to the "this", which will be a new object that is instantiated at some point. But within the scope of the initialize function addAll is undefined, because you are writing this within scope where "this" doesn't exist yet. Eventually an addAll property will get bound to "this", but here addAll is a property of a new object that you are passing into extend, that points to an anonymous function.

Upvotes: 1

Related Questions