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

相關問題