Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 776
LDK Avatar asked May 21 '11 01:05

LDK


People also ask

What is BindAll?

BindAll() function in underscore. js is used to bind the number of methods on the object. Each method is given a method name. It is handy to work with the event handlers.

How does Backbone JS work?

BackboneJS is a lightweight JavaScript library that allows to develop and structure the client side applications that run in a web browser. It offers MVC framework which abstracts data into models, DOM into views and bind these two using events.

Does backbone use jQuery?

By default Backbone will use: jQuery, // Zepto, or Ender; but the `setDomLibrary()` method lets you inject an // alternate JavaScript library (or a mock library for testing your views // outside of a browser).


2 Answers

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

like image 123
Georgii Ivankin Avatar answered Sep 24 '22 00:09

Georgii Ivankin


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   } }); 
like image 22
Johnny Oshika Avatar answered Sep 22 '22 00:09

Johnny Oshika