2013-09-29 164 views
0

我有一个与一个Model关联的EditorView子视图,它呈现一系列表单元素(input checkbox,textarea)。骨干事件被多次触发

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

这很好。

但是,当事件被连接到编辑子视图

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

会触发该事件多次......每一次以前加载EditorViews。就好像许多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 

感谢

的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); 
    } 
+0

jquery文档“使用.empty()。html(字符串)而不是.html(字符串),以便在将新字符串分配给元素之前从文档中删除元素。”实际上没有预期的功能 –

回答

1

骨干重视处理程序视图的根元素,所以当你创建具有相同根元素若干意见回调多次注册。它使用event bubbling来检测在子元素上触发的事件。问题是这一行:

el: ".editor", 

即使你删除所有的.editor内容,为元素处理器本身将保持。您需要将其删除,或者如果要保留它,则可以在创建新视图之前使用视图的undelegateEvents方法:它将删除先前附加的事件处理程序。

+0

哦。我懂了。这意味着虽然html元素消失了。事件可能仍然存在...... –

+0

@GabeRainbow不,不完全是。这是因为事件处理程序不会附加到'.isactive',而是附加到'.editor',即使您在编写'click .isactive'时也是如此。你永远不会删除'.editor'。 – zaquest

+0

好的。我懂了。所以你需要在初始化器或其他地方调用undelegateEvents。 –