Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: _.bindAll() in initialize - why is this used?

Tags:

I've been looking at some examples of backbone.js based application. I notice that in some (such as this example below) the underscore function _.bindAll() is used:

 initialize: function (args) {         _.bindAll(this, 'changeTitle');         this.model.bind('change:title', this.changeTitle);     }, 

whereas in others (such as the todo app below) do not:

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

What is the purpose of _.bindAll() in this context, and is it necessary?

like image 981
UpTheCreek Avatar asked Sep 09 '11 19:09

UpTheCreek


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.

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.

What is backbone JS model?

Model contains dynamic data and its logic. It performs various types of action on the data like validation, conversion, computed properties, access control etc. 1. It extends Backbone.


1 Answers

_.bindAll() changes this in the named functions to always point to that object, so that you can use this.model.bind(). Notice that in your second example, a third argument is passed to bind(); that's why using _.bindAll() isn't necessary in that case. In general, it's a good idea to use for any methods on the model that will be used as callbacks to events so that you can refer to this more easily.

like image 117
sciyoshi Avatar answered Oct 20 '22 17:10

sciyoshi