简体   繁体   English

如何使用骨干网将动态元素绑定到甚至从视图

[英]How to bind dynamic element to even from view using backbone.js

I am new in using backbone.js and jquery. 我是使用belion.js和jquery的新手。 I like to bind a dynamic generated element to click event in view. 我喜欢将动态生成的元素绑定到视图中的click事件。 hier is my code: hier是我的代码:

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();
    });  

}});      

where img.ImdDelete is the dynamically generate data of a table cell. 其中img.ImdDelete是动态生成表格单元格的数据。

the code in model is: 模型中的代码是:

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();

                            });

}});

My problem is that event is not bound to the model. 我的问题是事件未绑定到模型。 And i dont see the alert message. 而且我没有看到警报消息。

Well this is documented in backbone here: http://documentcloud.github.com/backbone/#View-delegateEvents 好吧,这在这里的主干中有记录: http : //documentcloud.github.com/backbone/#View-delegateEvents

In you View extend provide a events argument: 在您的View扩展中提供一个事件参数:

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

Define validate and delete as functions on your view and you are set. 在视图上将validate和delete定义为功能,您便已设置好。 There are many example of that in the backbone examples. 在主干示例中有很多示例。 Backbone uses jQuery delegate to properly delegate the events to the view. Backbone使用jQuery委托将事件正确委托给视图。 The added bonus is that delegate works almost the same way as live so you can add and remove element dynamically as you please (live is pretty much a delegate on the body). 增加的好处是,委托的工作方式与实时委托几乎相同,因此您可以根据需要动态地添加和删除元素(实时委托实际上是主体上的委托)。

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

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