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?
Takes your method, creates a copy with the context bound to 'ctx' and adds the copy as property.
This is a workaround for
jQuery.bind()
not allowing you to pass in a context. JQ will always call the callbacks with a undefined context. Backbone is built on jQuery.See here: http://backbonejs.org/#FAQ-this
_.bindAll()
changesthis
in 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 tothis
more easily.