是这些骨干/下划线.bind()方法之间的区别? [英] What is the difference between these Backbone/Underscore .bind() methods?
问题描述
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不起作用?
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?
推荐答案
有三个主要的差别; _。结合
一次只适用于一种方法,使钻营,并返回绑定的功能(这也意味着你可以使用 _绑定
上一个匿名函数):
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):
绑定的功能到对象,这意味着当函数被调用时,中的这个的将是在对象的值。或者,绑定的参数到功能以pre-填充它们,也被称为钻营
Bind a function to an object, meaning that whenever the function is called, the value of this will be the object. Optionally, bind arguments to the function to pre-fill them, also known as currying.
_。bindAll
结合众多的命名马上方法,不允许钻营,并绑定他们就地:
whereas _.bindAll
binds many named methods at once, doesn't allow currying, and binds the them in-place:
绑定了一些在对象的方法,由指定的方法名后,在每当他们调用该对象的上下文中运行。
Binds a number of methods on the object, specified by methodNames, to be run in the context of that object whenever they are invoked.
所以,code这两大块大致相当于:
So these two chunks of code are roughly equivalent:
// Bind methods (not names) one a time.
o.m1 = _.bind(o.m1, o);
o.m2 = _.bind(o.m2, o);
// Bind several named methods at once.
_.bindAll(o, 'm1', 'm2');
但没有 bindAll
等价于:
f = _.bind(o, o.m1, 'pancakes');
这使得 F()
同 o.m1('煎饼')
(这是<一个HREF =http://en.wikipedia.org/wiki/Currying>钻营)。
所以,当你这样说:
_.bindAll(this, 'render');
this.model.bind('change', this.render);
您要绑定的方法渲染
有一个这个
相匹配的电流这个
然后你结合 this.render
来的变化事件 this.model
。
You're binding the method render
to have a this
that matches the current this
and then you're binding this.render
to the change event on this.model
.
当你这样说:
this.model.bind('change', _.bind(this.render, this));
您在做同样的事情。而这个:
You're doing the same thing. And this:
_.bind(this.render, this);
this.model.bind('change', this.render);
因为你丢掉的返回值_不起作用。结合
(即你扔掉绑定功能)。
doesn't work because you're throwing away the return value of _.bind
(i.e. you throw away the bound function).
这篇关于是这些骨干/下划线.bind()方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!