Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I need to use _.bindAll() in Backbone.js?

Tags:

I am learning backbone.js, and feel confused on this: I am following the tutorial : http://arturadib.com/hello-backbonejs/

as you can see in the first example (1.js):

(function($){   var ListView = Backbone.View.extend({         el: $('body'), // attaches `this.el` to an existing element.      initialize: function(){       _.bindAll(this, 'render'); // fixes loss of context for 'this' within methods         this.render(); // not all views are self-rendering. This one is.     },      render: function(){       $(this.el).append("<ul> <li>hello world</li> </ul>");     }   });    var listView = new ListView();       })(jQuery); 

But if I comment out the sentence: _.bindAll(this, 'render');, this will still work. I have searched in google and someone said that the method bindAll() is necessary since if I switched my context, the calling of this.render may unavailable. I feel confused on the "context". and also could some one explain me when the calling (this.render) will unavailable?

like image 892
Anar Avatar asked Jan 25 '13 01:01

Anar


People also ask

What is bindAll?

bindAll() method 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.

What is the only method available in the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.

How does Backbone JS work?

BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.


1 Answers

For the example you've given _.bindAll(this, 'render'); isn't necessary but if you have callback functions where this can possibly be changed to the context of something else, then _bindAll() can be handy.

For instance:

initialize: function(){   _.bindAll(this, 'render', 'clickFunc'); }, events: {    'click .someElement': 'clickFunc' }, clickFunc: function(e) {    /** If you remove the clickFunc from the list of events in bindAll,            'this' will refer to the element that invoked the event.         Adding the clickFunc event in the _.bindAll, ensures that 'this' stays           as the view.    */   this /** <-- our focal point */ } 
like image 72
Dennis Rongo Avatar answered Sep 27 '22 21:09

Dennis Rongo