我让 View 监听集合上的“添加”事件。当处理程序触发时,上下文是 Collection,即使我使用 _.bindAll() 将其绑定(bind)到 View。这是一个错误,还是我不明白这是如何工作的? 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…}
最佳答案
将bindAll方法放在绑定(bind)到集合语句之前 这应该有效:
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);
关于javascript - bindAll() 似乎不适用于 Backbone View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22159292/