这些 Backbone/Underscore .bind() 方法有什么区别?
window.SomeView = Backbone.View.extrend({
initialize1: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
initialize2: function() {
this.model.bind('change', _.bind(this.render, this));
},
initialize3: function() {
_.bind(this.render, this);
this.model.bind('change', this.render);
},
});
在一些 SO 成员的帮助下,我能够让我的测试项目使用绑定方法initialize1和initialize2;我不明白的是为什么initialize3不起作用?
window.SomeView = Backbone.View.extrend({
initialize1: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
},
initialize2: function() {
this.model.bind('change', _.bind(this.render, this));
},
initialize3: function() {
_.bind(this.render, this);
this.model.bind('change', this.render);
},
});
With help from some SO members, I was able to get my test project working with binding methods initialize1 and initialize2; what I don't understand is why initialize3 doesn't work?
documentation: _.bind(function, object, [*arguments])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
主要有以下三个区别:
_.bind
一次仅适用于一种方法,允许柯里化,并且返回 绑定函数(这也意味着您可以在匿名函数上使用_.bind
):而
_.bindAll
一次绑定许多命名方法,不允许柯里化,并将它们绑定到位:所以这两段代码大致是等价的:
但是没有与此等效的
bindAll
:这使得
f()
与o.m1('pancakes ')
(这是柯里化)。因此,当您这样说时:
您将方法
render
绑定为具有与当前this
匹配的this
,然后绑定this.render
到this.model
上的更改事件。当你这样说时:
你也在做同样的事情。而这个:
不起作用,因为你扔掉了 _.bind 的返回值(即你扔掉了绑定函数)。
There are three main differences;
_.bind
only works on one method at a time, allows currying, and returns the bound function (this also means that you can use_.bind
on an anonymous function):whereas
_.bindAll
binds many named methods at once, doesn't allow currying, and binds the them in-place:So these two chunks of code are roughly equivalent:
But there is no
bindAll
equivalent to this:That makes
f()
the same aso.m1('pancakes')
(this is currying).So, when you say this:
You're binding the method
render
to have athis
that matches the currentthis
and then you're bindingthis.render
to the change event onthis.model
.When you say this:
You're doing the same thing. And this:
doesn't work because you're throwing away the return value of
_.bind
(i.e. you throw away the bound function).