window.SomeView = Backbone.View.extrend({
initialize1: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
initialize2: function() {
this.model.bind('change', _.bind(this.render, this));
},
initialize3: function() {
_.bind(this.render, this);
this.model.bind('change', this.render);
},
});
With help from some SO members, I was able to get my test project working with binding methods initialize1 and initialize2; what I don’t understand is why initialize3 doesn’t work?
documentation: _.bind(function, object, [*arguments])
There are three main differences;
_.bindonly works on one method at a time, allows currying, and returns the bound function (this also means that you can use_.bindon an anonymous function):whereas
_.bindAllbinds many named methods at once, doesn’t allow currying, and binds the them in-place:So these two chunks of code are roughly equivalent:
But there is no
bindAllequivalent to this:That makes
f()the same aso.m1('pancakes')(this is currying).So, when you say this:
You’re binding the method
renderto have athisthat matches the currentthisand then you’re bindingthis.renderto the change event onthis.model.When you say this:
You’re doing the same thing. And this:
doesn’t work because you’re throwing away the return value of
_.bind(i.e. you throw away the bound function).