2012-07-04 23 views
2

我需要將值傳遞給listView.template以便了解有關collection.length的模板。
我認爲一種選擇是重新定義serializeData方法以便以這種方式傳遞參數。CompositeView中的SerializeData

var ListView = Marionette.CompositeView.extend({ 

    initialize: function() { 
     this.collection.on('reset', this.serializeData, this); 
     this.collection.on('remove', this.serializeData, this); 
     this.collection.on('add', this.serializeData, this); 
    }, 

    serializeData: function() { 
     console.log(this.collection.length); 
     return { 
      has_tasks: this.collection.length > 0 
     }; 
    }, 

    // other codes 
}); 

當我開始appcollection尚未取這樣:

1.A)的collection.legth = 0
2.B)模板得到has_tasks = false預期。後

2.A)獲取collection.length is > 0
2.B)的serializeData被調用,所以它把has_tasks = true
2.C)模板似乎沒有渲染,因爲它保持了has_tasks = false

任何想法,因爲2.c

回答

3

最新Marionette通過調用視圖上的可選templateHelpers來解決此問題,以便爲視圖提供附加上下文。另外,您的事件綁定不是Marionette友好的,因爲它在卸載視圖時不會自動解除綁定。因此,所有你需要在你的觀點做的是:

var ListView = Marionette.CompositeView.extend({ 

    initialize: function() { 
     this.bindTo(this.collection, "add", this.render, this); 
     this.bindTo(this.collection, "remove", this.render, this); 
     this.bindTo(this.collection, "reset", this.render, this); 
    }, 

    templateHelpers: function() { 
     console.log(this.collection.length); 
     return { 
      has_tasks: this.collection.length > 0 
     }; 
    }, 

    // other codes 
}); 

但是請注意,你可能不希望重新呈現整個視圖和所有的子元素的每一個項目被添加或刪除的時間。更好的方法是隻更新顯示的計數。例如:

2

我只想使用類似:

​​

再次調用serializeData將會對你的看法沒有影響。您需要再次渲染以顯示新值(因爲render將通過再次調用serializeData來獲取數據)。

無論如何,將hasTask發送到模板的要點是什麼,因爲您可以訪問集合(因此它的長度)?

+0

發送hasTask的要點是顯示關於hasTask = false時的情況的模板部分。我應該改變一些東西嗎? IMH CompositeView模板不能訪問集合,只能訪問模型屬性。該物品可以訪問收藏。我對嗎? –

+0

您可以通過您的複合視圖模板中的console.log(this)來檢查。因爲我不使用與你一樣的堆棧,所以我不確定你有什麼。 –

+0

CompositeView有權訪問集合,但是'marionette.composed.view'呈現'model.attributes'沒有集合。 –

相關問題