我想捕获按钮的(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');
}
});
视图仅在事件起源于视图的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));