Why bindAll in backbone.js views?

There are several places in the main todo demo in the code where _.bindAll(this,...) . In particular, it is used in the initialize function for both views. As far as I can tell, you need to do the following:

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

But why do you need to do the above, when you can do it:

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

?

+48
May 21 '11 at 1:39
source share
3 answers

this.$ limits the jQuery context for the view element, so operations are faster.

Additionally, this.$('.todo-item') will not find your todo-item class items outside of your view element.

+36
May 21 '11 at 9:57
source share
β€” -

_.bindAll( this, ... ) needed not only for this.$( selector ).doSomething() , but in general, to make sure that this in your view method always points to the view itself.

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

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

Without _.bindAll( this, 'render' ) , when changing the this model to render will point to the model, and not to the view, so we will have neither this.el , nor this.$ , Or any other properties of the view available.

+93
Jun 18 2018-11-11T00:
source share

Compared to Backbone 0.5.2, you no longer need to use _.bindAll (this ...) in your views to set the context of the bind callback functions, since now you can pass the third argument to the binding (), which will set the context ( i.e. "this") 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 } }); 
+59
Aug 18 '11 at 5:15
source share



All Articles