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;
_.bind
only works on one method at a time, allows currying, and returns the bound function (this also means that you can use_.bind
on an anonymous function):whereas
_.bindAll
binds 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
bindAll
equivalent to this:That makes
f()
the same aso.m1('pancakes')
(this is currying).So, when you say this:
You're binding the method
render
to have athis
that matches the currentthis
and then you're bindingthis.render
to 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).