Javascript 当其中一个模型发生更改时,如何在Backbone.js中为集合视图附加事件处理程序?
我有一个呈现任务列表的视图:Javascript 当其中一个模型发生更改时,如何在Backbone.js中为集合视图附加事件处理程序?,javascript,model-view-controller,events,event-handling,backbone.js,Javascript,Model View Controller,Events,Event Handling,Backbone.js,我有一个呈现任务列表的视图: ProjectManager.Views.TasksIndex = Support.CompositeView.extend({ initialize: function() { _.bindAll(this, "render"); this.collection.bind("add", this.render); }, render: function () { this.renderTemplate(); this.
ProjectManager.Views.TasksIndex = Support.CompositeView.extend({
initialize: function() {
_.bindAll(this, "render");
this.collection.bind("add", this.render);
},
render: function () {
this.renderTemplate();
this.renderTasks();
...
},
renderTemplate: function() {
$(this.el).html(JST['tasks/index']({ tasks: this.collection }));
},
renderTasks: function() {
var self = this;
this.collection.each(function(task) {
// only display draft tasks
if (task.get('status') === "draft") {
var taskItem = new ProjectManager.Views.TaskItem({ model: task });
self.renderChild(taskItem);
self.$('#tasks-list').append(taskItem.el);
}
});
}
....
});
我为集合中的每个任务呈现一个视图。我希望能够删除任务。当用户单击任务的删除按钮后,我将任务模型上的状态属性设置为“已删除”。现在,我需要在TasksIndex视图中绑定一个事件处理程序来重新呈现集合。
我试过了
this.collection.bind("change", this.render);
但它不起作用。如何将在子视图中的模型上发生的事件传播到父视图?
当模型状态更改时,this.collection.bind('change',this.render)
应调用render
方法
可以添加console.log('render called')将代码>行添加到渲染方法,以查看模型状态更改时是否正在调用它
我认为正在调用render方法,但是其他地方的一些逻辑没有正确显示任务。您将这个.collection.bind(“change”,this.render)放在哪里;?模型的更改事件应该传播到它所属的集合中。是的,我很惊讶它不会传播到收藏中。但在我再次尝试后,它成功了(可能是模型视图中的其他错误)是的,这一次我再次尝试时它成功了(出于某些原因,每次删除任务时,甚至会调用两次render)。为了让代码正常工作,我确实把代码弄得乱七八糟,所以我可能无意中纠正了其他地方的一些逻辑。非常感谢。