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);
},
而在其他(如待办事项应用程序下面)不:
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.model.bind()
。请注意,在你的第二个例子中,第三个参数传递给绑定()
;这就是为什么使用 _。bindAll()
是不是在这种情况下,必要的。一般情况下,它是用于将用作回调事件对模型中的任何方法,使您可以参考一个好主意,这个
更容易。
_.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屋!