why do bindAll in backbone.js views?

20,148

Solution 1

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.

Solution 2

_.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 3

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
  }
});
Share:
20,148

Related videos on Youtube

LDK
Author by

LDK

Problem solving + JavaScript + Ruby = fun

Updated on March 19, 2020

Comments

  • LDK
    LDK about 4 years

    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);
    

    ?

  • Admin
    Admin over 12 years
    The line "this.model.bind('change', this.render, this)" just makes my head spin >.<
  • dira
    dira over 12 years
    Try coffeescript and its => operator.
  • Jonatan Littke
    Jonatan Littke about 12 years
    Do notice that this.bind (or this.model.bind) do a completely different thing than _.bind. Took me a while to realize.
  • brianc
    brianc over 10 years
    @JonatanLittke right, the backbone binds are an alias for 'on'
  • Alexander Mills
    Alexander Mills almost 9 years
    this is not recommended - it is more recommended to use this.listenTo(this.model,'change:id',this.render); because then the listeners will be removed when you destroy the view