我正在尝试了解他们在 Backbone 0.9.9 中所做的新更改。
目前我在理解 listenTo
和 on
之间的区别时遇到了问题:
收听
var View = Backbone.View.extend({
tagName: "div",
intialize: function() {
this.listenTo(this.model, 'change', this.render);
},
render: function() {
this.$el.empty();
this.$el.append('<p>hello world</p>');
}
});
开启
var View = Backbone.View.extend({
tagName: "div",
intialize: function() {
this.model.on('change', this.render, this);
},
render: function() {
this.$el.empty();
this.$el.append('<p>hello world</p>');
}
});
我听说 listenTo
允许使用 stopListening
取消订阅所有事件,例如当 View 被删除以避免内存泄漏时。
这是唯一的原因吗?
最佳答案
创建 View 时,listenTo
和on
都会添加事件处理。但是,当 View 被销毁时,listenTo
调用将 automatically remove the event handler .这prevents memory leaks和僵尸事件监听器。
因此,如果您想自己管理处理程序,请使用 on
。只需确保调用 off
。否则,调用 listenTo
。
关于javascript - Backbone 0.9.9 : Difference between listenTo and on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14041042/