Here’s an example of my collection view:
mod.AppListView = Backbone.View.extend({
initialize: function() {
var self = this
mod.collection.bind('add', self.addOne);
mod.collection.bind('reset', self.addAll);
_.bindAll(self, 'addOne', 'addAll');
this.addAll();
},
events: {
},
addOne: function(myModel) {
var view = new ListItemView({
model: myModel
});
},
addAll: function() {
mod.collection.each(this.addOne);
},
});
On initial run this works fine. But on subsequent resets addAll’s this becomes the collection instead of the view, and therefore addOne wouldn’t work.
To fix this I had to do:
mod.collection.bind('reset', self.addAll, this);
But I thought that was the point of _.bindAll? Shouldn’t that have set the this to be the view? Could this be explained? Is there a way to always ensure this points to the view and not the collection?
Thanks.
_.bindAllmust come before any reference to the method. You have it backwards.When you call
_.bindAll, it replaces the methods that you’ve specified with one that has been wrapped / proxied / decorated, to ensure the context is always set correctly. Since the method is being replaced, any reference that you make to the method must be done after the replacement happens. Otherwise the reference will be pointing to the original method and the_.bindAllwill appear to have not worked.As far as
_.bindAllvs the 3rd parameter… pick the one you like. I prefer passing in the 3rd parameter when calling.bind, but that’s just me. There are cases when I have to use_.bindAll, though. Both of them do the same thing, they just do it in a different way.