Search code examples
eventsbackbone.jsclick

How to catch click event in backbone


I want to catch the button's (addnewItem) click event but can't achieve it. What is wrong with the following code?

MyView = Backbone.View.extend({
    tagName: "table",
    render: function () {
        var rows = [];
        this.collection.each(function (row) {
            var rowView = new RowView({ model: row});
            rows.push(rowView.render().el);
        });
        this.$el.html(rows);
        $("#app-view").html("<h3>Items</h3><br/>").append(this.el).append("<br /><input type='button' class='btn btn-primary' value='Add new item' id='addNewItem' />");
        return this;
    },
    initialize: function () {
        this.listenTo(this.collection, "add", this.render);
    },
    events: {
        "click #addNewItem": "addNewItem"
    },
    addNewItem: function () {
        alert('Item added');
    }
});

Solution

  • A view only catches events this way if they originate inside the view's el. I can see from your render method that the button is outside the el.

    If it works in your html, you could fix this just by including your button in the el (which I think is just a default div). Your render method might now end with:

    this.$el.html(rows).append("<br /><input type='button' class='btn btn-primary' value='Add new item' id='addNewItem' />");
    $("#app-view").html("<h3>Items</h3><br/>").append(this.el);
    return this;
    

    An alternative is attaching the event in a more conventional way. In your initialize method you could add:

    $("#app-view").on('click', '#addNewItem', this.addNewItem);
    

    or, if the this keyword is important in the addNewItem method then try:

    $("#app-view").on('click', '#addNewItem', this.addNewItem.bind(this));