简体   繁体   English

当其中一个模型被更改时,如何为Backbone.js中的集合视图附加事件处理程序?

[英]How can I attach event handler for a collection view in Backbone.js when one of the models is changed?

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. 现在我需要在TasksIndex视图中绑定一个事件处理程序来重新呈现集合。
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? 如何将子视图中模型上发生的事件传播到父视图?

this.collection.bind('change', this.render) should call the render method when the model status is changed. this.collection.bind('change', this.render)应在模型状态更改时调用render方法。

Can you add a console.log('render called'); 你能添加一个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. 我正在考虑调用render方法,但在其他地方有一些逻辑没有正确显示任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM