当其中一个模型发生更改时,如何为 Backbone.js 中的集合视图附加事件处理程序?
我有一个呈现任务列表的视图:
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);
,但没有成功。
如何将子视图中模型上发生的事件传播到父视图?
I have a view that renders a tasks list:
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);
}
});
}
....
});
I render a view for each task that is in the collection. I would like to be able to delete a task.
I got to the point when after user clicks a delete button for a task I set a status attribute on task model to "deleted". Now somehow I need to bind an event handler in my TasksIndex view to re-render the collection.
I tried
this.collection.bind("change", this.render);
but it didn't work.
How can I propagate event that happened on the model in the child view to the parent view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当模型状态更改时,
this.collection.bind('change', this.render)
应调用render
方法。您可以在渲染方法中添加一个
console.log('render called');
行,以查看模型状态更改时是否正在调用它。我认为正在调用渲染方法,但其他地方有一些逻辑未正确显示任务。
this.collection.bind('change', this.render)
should call therender
method when the model status is changed.Can you add a
console.log('render called');
line to your render method to see if the it's being called when the model status is changed.I'm thinking the render method is being called but there's some logic elsewhere that is not correctly displaying the tasks.