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);
?
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.
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.
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).
_.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.
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 } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With