简体   繁体   English

骨干事件多次被解雇

[英]backbone event fired many times

I have an EditorView subview associated with one Model that renders a series of form elements (input checkbox, textarea). 我有一个与一个Model关联的EditorView子视图,该子视图呈现了一系列表单元素(输入复选框,文本区域)。

My ListView creates one and only one Editor sub view. 我的ListView创建一个并且只有一个 Editor子视图。 ListView creates the EditorView by way of new EditorView(model: this.model). render(); ListView通过new EditorView(model: this.model). render();创建new EditorView(model: this.model). render(); new EditorView(model: this.model). render(); on a click of an item in the ListView. 单击ListView中的项目。

That works great. 效果很好。

But, when an event is attached to the Editor subview 但是,当事件附加到“编辑器”子视图时

  // Bind to all properties in the view
  events: {
     "click input.isactive":  "editActive"
  },

The event gets fired multiple times...once per previously loaded EditorViews. 该事件被触发多次...每个以前加载的EditorViews一次。 As if the html for many was still present. 好像很多HTML仍然存在。 But checking the DOM (in Firefox) shows the html for only one EditorView. 但是检查DOM(在Firefox中)仅显示一个EditorView的html。

I use .html(string) in EditorView, which I thought would replace the previous html within the 'el' element. 我在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

Thanks 谢谢

The EditorView 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 attaches handlers to a root element of a view, so callbacks are registered multiple times when you create several views with the same root element. Backbone将处理程序附加到视图的根元素,因此当您使用相同的根元素创建多个视图时,回调会被多次注册。 It uses event bubbling to detect events that were triggered on a child element. 它使用事件冒泡来检测在子元素上触发的事件。 The problem is with this line: 问题在于此行:

el: ".editor",

Even if you remove all of the contents of .editor , handlers for the element itself will stay. 即使删除.editor所有内容,该元素本身的处理程序也会保留。 You need either to delete it, or if you want to keep it you can use the undelegateEvents method of the view before creating a new one: it will remove previously attached event handlers. 您需要删除它,或者如果想要保留它,则可以在创建新视图之前使用视图的undelegateEvents方法:它将删除以前附加的事件处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM