2015-09-02 42 views
2

我遇到了一個問題,在我的Marionette CompositeView中正在調用渲染,這是正確的,問題在於我正在獲取initialize中的集合數據,並且希望在渲染髮生。目前我正在運行this.render()內部完成的方法獲取重新呈現,但這會導致問題,因爲現在我有2個視圖每個模型。任何人都可以推薦我可以如何正確地防止這個初始渲染或防止重複的意見。 1條目將輸出view1和view2。防止Marionette CompositeView渲染直到抓取完成

JS CompositeView中

initialize: function() { 
      var self = this; 

      this.teamsCollection = new TeamsCollection(); 

      this.teamsCollection.fetch().done(function() { 
       self.render(); 
      }); 
     }, 

回答

0

首先,我不相信有一種方法來停止渲染顧左右而言他,但你必須圍繞着一堆方式。

選項1:首先獲取數據,然後創建視圖並在完成時將數據傳遞給它。

//before view is rendered, this is outside of your view code. 
var teamsCollection = new TeamsCollection(); 

teamsCollection.fetch().done(function(results) { 
    var options = {res: results}; 
    var myView = new CompositeView(options); 
    myView.setElement(/* your element here */).render(); 
}); 

選項2:

// don't use render method, use your own 
initialize: function() { 
    var self = this; 

    this.teamsCollection = new TeamsCollection(); 

    this.teamsCollection.fetch().done(function() { 
     self.doRender(); 
    }); 
}, 
render: function(){}, // do nothing 
doRender: function(){ 
    // override render here rather than using default 
} 

方案三:(如果使用模板)

// if you have a template, then you can simply pass in a blank one on initialization 
// then when the fetch is complete, replace the template and call render again 
initialize: function() { 
    var self = this; 
    this.template = "<div></div"; // or anything else really 
    this.teamsCollection = new TeamsCollection(); 

    this.teamsCollection.fetch().done(function() { 
     self.template = /* my template */; 
     self.render(); 
    }); 
}, 

在現實中,我需要更多的信息。視圖是如何創建的?這是一個地區嗎?它是動態添加的嗎?你使用模板嗎?你能提供更多的代碼嗎?

+0

謝謝你,這是動態創建和使用區域!我確實使用模板,並喜歡你的選擇3.我會更新我的問題,更多的信息 – styler

+0

嗯實際上第三個選項不會擺脫這樣的事實,即爲每個模型創建雙視圖,因爲渲染仍然會每個模型發生兩次? – styler

+0

好吧,我希望我的回答至少能指出你正確的方向。但是使用區域意味着你希望Marionette爲你自動渲染東西,所以你唯一的選擇是渲染一些不可見的東西,並且使用一個什麼都不做的類(第一次渲染)。然後,一旦你獲得數據,切換類和模板並重新渲染。 – SoluableNonagon