2011-05-09 30 views
1

我是新使用backbone.js和jquery。 我喜欢绑定一个动态生成的元素来点击视图中的事件。 hier是我的代码:如何绑定动态元素甚至从视图使用backbone.js

InvoiceView = Backbone.View.extend({ 
initialize: function() { 
    var _this = this; 

     $('input.BtnValidate').bind('click', function() { 
     _this.model.save(); 
     _this.model.createTable(); 
     _this.model.updateTotalAmount(); 
     _this.model.clear(); 
    }); 

    $('img.ImgDelete').bind('click', function() {    
     _this.model.RemoveTableRow(); 
     _this.model.updateTotalAmount(); 
    }); 

}});  

其中img.ImdDelete是动态生成表格单元格的数据。

中的代码模式是:

InvoiceModel = Backbone.Model.extend({ 
createTable: function() { 
    var lastRow = $('#TblInvoiceList tr:last'); 
    var newRow = $('<tr>'); 
    newRow.append($('<td>').text($('input.Name').val()), $('<td>').text($('input.GrossAmount').val())); 
    newRow.append("<td class='center'><img class='ImgDelete' src='image/ButtonDelete.png' /></td>"); 
    lastRow.before(newRow); 
    $("tr:nth-child(even)").addClass("white"); 
    lastRow.addClass("tr.last"); 
     }, 

RemoveTableRow: function() { 
    alert("delete the row"); 
      var deletedRow = $('#TestTable td img.ImgDelete'); 
      S(deletedRow).parent().parent().remove(); 

          }); 

}}); 

我的问题是事件不会绑定到模型。我没有看到提醒消息。

回答

1

嗯,这是记录在这里骨干: http://documentcloud.github.com/backbone/#View-delegateEvents

在您查看扩展提供了事件的说法:

events : { 
    "click input.BtnValidate" : "validate", 
    "click img.ImgDelete" : "delete" 
}, ... 

定义验证并删除作为您的视图功能,你都设置。骨干例子中有很多例子。 Backbone使用jQuery委托来正确地将事件委托给视图。额外的好处是,代理的工作方式与现场几乎相同,因此您可以随意添加和删除元素(实际上几乎是代表身体的代表)。

相关问题