Javascript 主干收集';添加';事件未触发
我的集合中有一个事件侦听器,它侦听“添加”事件,该事件似乎仅在添加我在路由器中添加的示例数据时触发,但在我的视图中添加更多模型时不会触发,两者的代码如下所示: 收藏:Javascript 主干收集';添加';事件未触发,javascript,backbone.js,Javascript,Backbone.js,我的集合中有一个事件侦听器,它侦听“添加”事件,该事件似乎仅在添加我在路由器中添加的示例数据时触发,但在我的视图中添加更多模型时不会触发,两者的代码如下所示: 收藏: Application.Collection.extend({ name: "todos/todos", initialize: function() { this.on("add", console.log("added")); }, url: "/todo-application/todos" });
Application.Collection.extend({
name: "todos/todos",
initialize: function() {
this.on("add", console.log("added"));
},
url: "/todo-application/todos"
});
路由器(触发事件):
视图(这不会触发事件):
视图中的collection.add
确实有效,因为模型已添加到集合中并显示在屏幕上,但集合仅在添加样本数据时在初始页面加载时为我提供console.log()
编辑:
根据我的主干Chrome扩展,事件确实正在触发,但由于某些原因,此事件绑定不起作用,我尝试使用
this.listenTo
而不是。on
当您在对象上使用on
函数时,您正在将回调
绑定到该对象上的事件
,而回调
必须是一个函数,如下所示:
this.on("add", function() { console.log("added"); });
构造视图时是否传入集合?e、 g.
新视图({collection:collection})
Application.View.extend({
name: "todos/index",
events: {
"submit form": function(event) {
event.preventDefault();
var attrs = this.serialize();
this.collection.add(attrs);
this.$('input[name=title]').val('');
}
}
});
this.on("add", function() { console.log("added"); });