骨干现在默认执行 _.bindAll 吗?
本教程建议我们需要执行 _.bindAll
在我们的函数中获取 this
的正确值。 Backbone 似乎不再需要 _.bindAll
。以下代码将相同的内容记录两次:
var TestView = Backbone.View.extend({
initialize: function () { _.bindAll(this, 'func1'); },
func1: function () { console.log(this); },
func2: function () { console.log(this); }
});
var testView = new TestView();
testView.func1();
testView.func2();
我是否正确地假设不再需要 bindAll
,或者我只是犯了一个愚蠢的错误?
This tutorial suggests that we need to do _.bindAll
to get the correct value of this
in our functions. It seems that _.bindAll
is no longer required with Backbone. The following code logs the same thing twice:
var TestView = Backbone.View.extend({
initialize: function () { _.bindAll(this, 'func1'); },
func1: function () { console.log(this); },
func2: function () { console.log(this); }
});
var testView = new TestView();
testView.func1();
testView.func2();
Am I correct in assuming that bindAll
is no longer required, or am I just making a stupid mistake?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当该方法在类的上下文之外调用时,它仍然是必要的。既然您在上下文中回忆了它,那么您不需要它并不是一个错误。
正如
_.bindAll
的下划线文档中所述 (http://documentcloud. github.com/underscore/#bindAll),它“对于绑定将用作事件处理程序的函数非常方便,否则将使用相当无用的this
来调用。”您还可以将它用于需要创建回调的方法。要了解回调有何差异,请查看此小提琴。 http://jsfiddle.net/joshvermaire/YQdZu/
It is still necessary when the method is called out of context of the Class. Since you'recalling it in context, it isn't a mistake that you haven't needed it.
As mentioned in the underscore documentation for
_.bindAll
(http://documentcloud.github.com/underscore/#bindAll), it's "very handy for binding functions that are going to be used as event handlers, which would otherwise be invoked with a fairly uselessthis
." You would also use it for methods where you need to create a callback.To see how there are differences for callbacks, look at this fiddle. http://jsfiddle.net/joshvermaire/YQdZu/