我使用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>