why do bindAll in backbone.js views?
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
}
});
Related videos on Youtube
Comments
-
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 theinitialize
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 over 12 yearsThe line "this.model.bind('change', this.render, this)" just makes my head spin >.<
-
dira over 12 yearsTry coffeescript and its => operator.
-
Jonatan Littke about 12 yearsDo notice that
this.bind
(orthis.model.bind
) do a completely different thing than_.bind
. Took me a while to realize. -
brianc over 10 years@JonatanLittke right, the backbone binds are an alias for 'on'
-
Alexander Mills almost 9 yearsthis 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