Backbone.js: _.bindAll() 初始化 - 为什么使用它? [英] Backbone.js: _.bindAll() in initialize - why is this used?
问题描述
我一直在查看一些基于backbone.js 的应用程序示例.我注意到在一些(例如这个例子 下面)使用下划线函数 _.bindAll()
:
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);
},
而在其他应用程序中(例如下面的 todo 应用)不:
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);
},
_.bindAll()
在这种情况下的目的是什么,是否有必要?
What is the purpose of _.bindAll()
in this context, and is it necessary?
推荐答案
_.bindAll()
将命名函数中的 this
更改为始终指向该对象,因此你可以使用this.model.bind()
.请注意,在您的第二个示例中,第三个参数被传递给 bind()
;这就是为什么在这种情况下不需要使用 _.bindAll()
.一般来说,最好将模型上的任何方法用作事件回调,以便您可以更轻松地引用this
.
_.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.
这篇关于Backbone.js: _.bindAll() 初始化 - 为什么使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!