0

我有渲染的任务列表视图:如何在一个模型更改时为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); 

,但没有奏效。
如何将发生在子视图模型上的事件传播给父视图?

+1

你在哪里放置this.collection.bind(“change”,this.render);?模型的更改事件应传播到其拥有的集合中。 – 2012-01-05 00:59:27

+0

我把它放在初始化中。是的,我很惊讶它不会传播到收藏。但是,当我再次尝试它的工作(可能是其他模型的视图是错误的) – lanan 2012-01-05 22:46:54

回答

2

this.collection.bind('change', this.render)应在模型状态更改时调用render方法。

你可以添加一个console.log('render called');行到你的render方法,看看它是否在模型状态改变时被调用。

我在想,渲染方法正在被调用,但有一些逻辑是不正确显示任务。

+0

是的,这一次,当我再次尝试工作(由于某些原因,每次我删除任务时渲染甚至被调用两次)。我弄乱了我的代码试图让它工作,所以我可能无意中纠正了其他地方的一些逻辑。谢谢! – lanan 2012-01-05 22:44:25

相关问题