2012-05-21 45 views
0

我的問題很可能需要一個非常簡單的答案,但我無法輕鬆找到答案。_.bind所有功能

我正在研究的一個Backbone應用程序有幾個視圖。在定義不同視圖時,我在初始化函數中使用_.bindAll將「this」視圖對象與視圖的渲染函數連接起來。例如:

DiscussedItemView = Backbone.View.extend({ 
    ... 
     initialize: function() { 
      _.bindAll(this, "render"); 
     }, 


     render: function() {  

      this.$el.attr('id', 'li-meeting-task-' + this.model.getId()); 

      this.$el.html(JST['tasks_sandbox/agenda_task_item']({ 
       taskName : this.model.getName(), 
       taskId  : this.model.getId() 
      })); 

      return this; 
     }, 
    ... 
}); 

要創建DiscussedItemView的新實例,我做了以下內容:

... 
     var discussion_agenda_row = new DiscussedItemView({model: task}); 
     discussion_agenda_row.render(); 
     this.$('#meeting-items-list').append(discussion_agenda_row.$el); 
... 

的代碼工作正常。不過,我不明白爲什麼需要在discussion_agenda_row上顯式使用render()函數。我認爲新的DiscussedItemView實例的初始化會自動調用渲染函數,但如果我刪除了discussion_agenda_row.render();行,則HTML將不會顯示。我錯在哪裏?

謝謝 亞歷山德拉

回答

1

視圖響應模型中的更改。在你的代碼中,你並沒有改變模型,所以視圖沒有響應。您還沒有將視圖設置爲偵聽器來對模型更改進行建模。什麼,你可以在你的初始化做的是這樣的:

initialize : function() { 
    //this will tell the view to render when the model 
    //triggers a "change" event 
    this.model.on("change", this.render, this); 

    //this will make the model throw the change event 
    //and since the view is listening to "change," render will be invoked. 
    this.model.fetch(); 
} 

所有這一切說,如果你沒有做任何的讀取和數據僅僅是在有你的模型,你仍然必須顯式調用視圖.render()。在任何情況下,對於優秀的MVC,我仍然會讓視圖監聽模型中的變化,以便它能夠正確地更新自己的響應。

+0

謝謝 - 您的答案很容易遵循。現在我明白了,如果你在初始化函數_.bindAll(this,「render」)中使用,你可以在this.model.on()中省略「this」參數,只寫this.model.on(「改變「,this.render),因爲上下文已經保存。 – Alexandra

+0

是的,你完全可以這樣做,但我寧願在「on」中指定上下文,而不是進行兩個調用。當你這樣做時,你不需要調用bindAll。 –

2

不,render沒有自動initialize調用。應用程序中的其他組件(例如路由器或其他視圖)將告訴您的視圖何時呈現它自己。