This tutorial suggests that we need to do _.bindAll
to get the correct value of this
in our functions. It seems that _.bindAll
is no longer required with Backbone. The following code logs the same thing twice:
var TestView = Backbone.View.extend({
initialize: function () { _.bindAll(this, 'func1'); },
func1: function () { console.log(this); },
func2: function () { console.log(this); }
});
var testView = new TestView();
testView.func1();
testView.func2();
Am I correct in assuming that bindAll
is no longer required, or am I just making a stupid mistake?
It is still necessary when the method is called out of context of the Class. Since you'recalling it in context, it isn't a mistake that you haven't needed it.
As mentioned in the underscore documentation for
_.bindAll
(http://documentcloud.github.com/underscore/#bindAll), it's "very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly uselessthis
." You would also use it for methods where you need to create a callback.To see how there are differences for callbacks, look at this fiddle. http://jsfiddle.net/joshvermaire/YQdZu/