lanan
lanan

Reputation: 2752

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?

Upvotes: 0

Views: 1030

Answers (1)

Paul
Paul

Reputation: 18597

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.

Upvotes: 2

Related Questions