简体   繁体   中英

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

I am new in using backbone.js and jquery. I like to bind a dynamic generated element to click event in view. hier is my code:

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.

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

In you View extend provide a events argument:

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

Define validate and delete as functions on your view and you are set. There are many example of that in the backbone examples. Backbone uses jQuery delegate to properly delegate the events to the view. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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