2014-08-29 30 views
1

我有一個按模型的datetime屬性排序的集合。每當一天發生變化時,我都需要顯示'分隔視圖'。我正在考慮使用CollectionView來顯示數據。我在正確的軌道上嗎?在CollectionView中顯示分隔符視圖

最終的結果會是這個樣子:

1st of September (separator view) 
----------------------------- 
Model1 
Model2 

2nd of September (separator view) 
----------------------------- 
Model3 

回答

0

的解決方案是延長的CollectionView的appendHtml方法。

appendHtml: (collectionView, itemView, index) -> 
    if @_isDayChanged index 
    itemView.separator = true 
    itemView.render() 
    super 
0

我使用CompositeView的列表來按月分組收集項目。你可以很容易地將它適應於幾天。

let ItemView = Marionette.ItemView.extend({ 
    ... 
}); 

let ListView = Marionette.CompositeView.extend({ 
    childView: ItemView, 
    template: template, 
    childViewContainer: '.items', 

    filter(child) { 
    return child.get('month') === this.model.get('month'); 
    } 
}); 

let MonthGroupedListView = Marionette.CollectionView.extend({ 
    childView: ListView, 

    childViewOptions(item, index) { 
    return { 
     model: item, 
     collection: this.getOption('collection') 
    }; 
    }, 

    initialize() { 
    // Passed collection remains in this.options.collection 
    // this.collection will contain distinct months 
    this.collection = new Backbone.Collection(); 
    this.reset(); 

    this.listenTo(this.options.collection, 'sync update', this.reset); 
    }, 

    reset() { 
    // Find distnct months and put them into the collection 
    let months = _.uniq(this.options.collection.map((model) => model.get('month'))); 

    this.collection.reset(_.map(months, (month) => ({month}))); 
    } 

}); 

從結果下面的數據應該是三組ListView

let data = [ 
    { id: 1, month: '2015-01', title: "January item 1" }, 
    { id: 2, month: '2015-01', title: "January item 2" }, 
    { id: 3, month: '2015-02', title: "February item 1" }, 
    { id: 4, month: '2015-05', title: "May item 1" }, 
    { id: 5, month: '2015-05', title: "May item 2" }, 
    { id: 6, month: '2015-05', title: "May item 3" } 
]; 

let view = new MonthGroupedListView({ 
    collection: new Backbone.Collection(data) 
}); 

ListView模板看起來是這樣的:

<div class="month-header"> 
    {{month}} 
</div> 
<ul class="items"> 
    {{-- Here ItemView elements will be rendered --}} 
</ul>