Backbone.js: _.bindAll() in initialize - why is this used?
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 (a开发者_如何学编程rgs) {
_.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()
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.
In Detail: _.bind(ctx, 'method')
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
精彩评论