Eri*_*num 9 events views listener backbone.js
我不明白在视图中的初始化函数中放置"click"侦听器并将其放在同一视图中的events对象之间的区别.他们都监听DOM事件和触发函数,对吧?有什么不同?
例如:
var ViewName = Backbone.View.extend({
initialize: function(){
this.$el.on("eventName", this.functionName, this)
},
functionName: function(){
//whatever
}
});
Run Code Online (Sandbox Code Playgroud)
与:
var ViewName = Backbone.View.extend({
events: { "eventName": "fucntionName" }
},
functionName: function(){
//whatever
}
});
Run Code Online (Sandbox Code Playgroud)
gbs*_*ice 12
当你这样做时:
var ViewName = Backbone.View.extend({
initialize: function(){
this.$el.on("eventName", this.functionName, this)
},
functionName: function(){
//whatever
}
});
Run Code Online (Sandbox Code Playgroud)
在删除视图时,您必须手动取消绑定事件.所以,你必须做的事情如下:
var ViewName = Backbone.View.extend({
initialize: function(){
this.$el.on("eventName", this.functionName, this)
},
functionName: function(){
//whatever
},
remove: function() {
this.$el.off("eventName", this.functionName);
Backbone.View.prototype.remove.apply(this, arguments);
}
});
Run Code Online (Sandbox Code Playgroud)
如果您使用events散列,Backbone会在删除视图时处理取消分配事件.这一点在Backbone.js注释源的这一节中都有解释.