如何在骨干网中捕获点击事件

问题描述 投票:0回答:1

我想捕获按钮的(addnewItem)click事件,但无法实现。以下代码有什么问题?

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');
    }
});
events backbone.js click
1个回答
1
投票

视图仅在事件起源于视图的el内部时才以这种方式捕获事件。我可以从您的渲染方法中看到该按钮在el之外。

如果它在您的html中有效,您可以通过在el中添加按钮来解决此问题(我认为这只是默认的div)。您的渲染方法现在可能以:

结尾
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;

一种替代方法是以更常规的方式附加事件。在initialize方法中,您可以添加:

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

或者,如果this关键字在addNewItem方法中很重要,请尝试:

$("#app-view").on('click', '#addNewItem', this.addNewItem.bind(this));
© www.soinside.com 2019 - 2024. All rights reserved.