When I sync my collection, the server returns a JSON object which I want to add as new models to my collection. I’ve set it up like this:
syncCollection: function() {
Backbone.sync('create', this, {
success: function (msg) {
console.log(this);
this.add(msg, {at: 0});
}
}, this);
}
The problem is that ‘this’ doesn’t seem to point to the collection, instead it is defaulting to the global window object. I have attempted to bind this to the collection but it doesn’t seem to work:
initialize: function() {
_.bindAll(this, 'syncCollection');
},
How can I use .bind to ensure that this points to the collection and not the window object?
Add
var that = thisat the beginning of the outer function(i.e. just beforeBackbone.sync), and replacethiswiththatin the inner function(i.e.success).Note: In JavaScript
thisalways refers to the owner of the function we’re executing, or rather, to the object that a function is a method of.BTW, you don’t have to use
_.bindAll,_.bindis enough.