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?
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.
There is only method named "start" can be used to manipulate the Backbone. js history.
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.
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 */ }
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