在CollectionView中显示分隔符视图

时间:2014-08-29 13:24:19

标签: marionette

我有一个按照型号的datetime属性排序的Collection。我需要显示一个分隔符视图'每当变化时。我正在考虑使用CollectionView来显示数据。我是在正确的轨道上吗?

最终结果如下所示:

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

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

2 个答案:

答案 0 :(得分:0)

解决方案是扩展CollectionView的appendHtml方法。

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

答案 1 :(得分: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>