骨干现在默认是_.bindAll吗?

Ran*_*lue 2 backbone.js

本教程建议我们需要在函数中_.bindAll获取正确的值this._.bindAllBackbone 似乎不再需要它.以下代码将相同的内容记录两次:

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();
Run Code Online (Sandbox Code Playgroud)

假设bindAll不再需要,或者我只是犯了一个愚蠢的错误,我是否正确?

jos*_*ire 5

当该方法被调用超出类的上下文时,仍然是必要的.由于您在上下文中回顾它,因此您不需要它并不是一个错误.

正如_.bindAll(http://documentcloud.github.com/underscore/#bindAll)的下划线文档中所提到的,它"对于将用作事件处理程序的绑定函数非常方便,否则将被调用相当无用this".您还可以将它用于需要创建回调的方法.

要了解回调的差异,请看这个小提琴.http://jsfiddle.net/joshvermaire/YQdZu/