why do bindAll in backbone.js views?

In backbone's todo demo the code has a few spots where _.bindAll(this,...) is used. Specifically it's used in the initialize function of both views. As far as I can tell it's necessary to do the following:

this.$('.todo-content').text(content);

But why would one want to do the above, when one can do:

$('.todo-content').text(content);

?


Solution 1:

_.bindAll( this, ... ) is necessary not only for this.$( selector ).doSomething() but generally to be sure that this in your view's method is always pointing to the view itself.

For example, if we want to refresh our view when the model changes, we bind the view's render method to the model's change event:

initialize: function() {
    this.model.bind( 'change', this.render );
},

Without _.bindAll( this, 'render' ), when the model changes this in render will be pointing to the model, not to the view, so we won't have neither this.el nor this.$ or any other view's properties available.

Solution 2:

As of Backbone 0.5.2, it's no longer necessary to use _.bindAll(this...) in your views to set the context of the "bind" callback functions, as you can now pass a 3rd argument to bind() that will set the context (i.e. "this") of the callback.

For example:

var MyView = Backbone.View.extend({
  initialize: function(){
    this.model.bind('change', this.render, this);
  },
  render: function(){
    // "this" is correctly set to the instance of MyView
  }
});

Solution 3:

this.$ limits jQuery's context to the view's element, so operations are quicker.

Additionaly, this.$('.todo-item') won't find your elements with todo-item class outside your view's element.