[英]backbone event fired many times
我有一个与一个Model
关联的EditorView子视图,该子视图呈现了一系列表单元素(输入复选框,文本区域)。
我的ListView创建一个并且只有一个 Editor子视图。 ListView通过new EditorView(model: this.model). render();
创建new EditorView(model: this.model). render();
new EditorView(model: this.model). render();
单击ListView中的项目。
效果很好。
但是,当事件附加到“编辑器”子视图时
// Bind to all properties in the view
events: {
"click input.isactive": "editActive"
},
该事件被触发多次...每个以前加载的EditorViews一次。 好像很多HTML仍然存在。 但是检查DOM(在Firefox中)仅显示一个EditorView的html。
我在EditorView中使用.html(string),我认为它将替换'el'元素中的先前html。
var compiledTemplate = _.template( Template, data ); // Merge model with template
this.$el.html( compiledTemplate ); // replace the previous html if any. ?? OR NOT!! SOAD
谢谢
EditorView
el: ".editor",
tagName: "ul",
className : "striped",
events: {
"click .isactive": "editActive"
},
render : function() {
var data = {
item: this.model,
_: _
};
var compiledTemplate = _.template( Template, data ); // Merge model with template
this.$el.empty().html( compiledTemplate ); // replace the previous html
return this;
},
editActive: function(e) {
e.preventDefault();
var x = this.$('.isactive').prop('checked'); // property of input checkbox
alert('click'+x);
var y = this.model.set('Active', x);
}
Backbone将处理程序附加到视图的根元素,因此当您使用相同的根元素创建多个视图时,回调会被多次注册。 它使用事件冒泡来检测在子元素上触发的事件。 问题在于此行:
el: ".editor",
即使删除.editor
所有内容,该元素本身的处理程序也会保留。 您需要删除它,或者如果想要保留它,则可以在创建新视图之前使用视图的undelegateEvents
方法:它将删除以前附加的事件处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.