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?
_.bindAll()changesthisin the named functions to always point to that object, so that you can usethis.model.bind(). Notice that in your second example, a third argument is passed tobind(); 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 tothismore easily.