代码之家  ›  专栏  ›  技术社区  ›  Gabe Rainbow

骨干事件被多次激发

  •  0
  • Gabe Rainbow  · 技术社区  · 11 年前

    我有一个EditorView子视图与一个关联 Model 它呈现一系列表单元素(输入复选框、文本区域)。

    我的ListView创建 一个也是唯一一个 编辑器子视图。ListView通过以下方式创建EditorView new EditorView(model: this.model). render(); 单击ListView中的项目。

    这很管用。

    但是,当事件附加到编辑器子视图时

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

    该事件被多次触发。。。每一次 先前 加载的编辑器视图。就好像许多人的html仍然存在一样。但是检查DOM(在Firefox中)只显示一个EditorView的html。

    我在EditorView中使用了.html(字符串),我认为它会取代'el'元素中以前的html。

         var compiledTemplate = _.template( Template, data ); // Merge model with template
         this.$el.html( compiledTemplate );  // replace the previous html if any. ?? OR NOT!! SOAD
    

    谢谢

    编辑器视图

      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);
      }
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   1983    11 年前

    Backbone将处理程序连接到视图的根元素,因此当您使用同一根元素创建多个视图时,会多次注册回调。它使用 event bubbling 以检测在子元素上触发的事件。问题出在这一行:

    el: ".editor",
    

    即使您删除了的所有内容 .editor ,元素本身的处理程序将保留。你需要删除它,或者如果你想保留它,你可以使用 undelegateEvents 方法:它将删除以前附加的事件处理程序。