简体   繁体   中英

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.
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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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