【问题标题】:bindAll() seems not to work in backbone ViewbindAll() 似乎在骨干视图中不起作用
【发布时间】:2014-03-03 22:54:18
【问题描述】:

我让 View 监听 Co​​llection 上的“添加”事件。当处理程序触发时,上下文是集合,即使我使用 _.bindAll() 将它绑定到视图。这是一个错误,还是我不明白它是如何工作的? jsfiddle

V = Backbone.View.extend({
    initialize: function (options) {
        this.collection.on('add', this.onAdd);
        _.bindAll(this, 'onAdd');
    },
    onAdd: function () { console.log(this); }
});
c = new Backbone.Collection();
v = new V({collection:c});
c.add(new Backbone.Model());

输出:

e.Collection {length: 1, models: Array[1], _byId: Object, _events: Object, on: function…}

【问题讨论】:

    标签: javascript backbone.js underscore.js backbone-events backbone.js-collections


    【解决方案1】:

    将 bindAll 方法放在绑定到集合语句之前 这应该有效:

    V = Backbone.View.extend({
    initialize: function (options) {
        _.bindAll(this, 'onAdd');
        this.collection.on('add', this.onAdd);
    
    },
    onAdd: function () { console.log(this); }
    

    });

    更新: 通过在 .on() 方法中应用上下文,可以不使用 _.bindAll 方法

    this.collection.on('add', this.onAdd, this);
    

    【讨论】:

    • 这是正确的。 _.bindAll 正在用一个新函数替换 onAdd,当你在调用它之前传递 this.onAdd 时,你传递的是对旧的、未绑定的版本的引用。
    • 另外,更好的解决方案是在 on 声明中传递上下文。即this.collection.on('add', this.onAdd, this);
    【解决方案2】:

    您的问题是,当您的调用 this.collection.on('add', this.onAdd); 首先一个事件绑定到没有上下文的 onAdd 函数(this = 触发时的集合)并且调用 _.bindAll(this, 'onAdd'); 时不会覆盖它。

    尝试更改顺序:

        _.bindAll(this, 'onAdd');
        this.collection.on('add', this.onAdd);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 2011-07-31
      相关资源
      最近更新 更多