【问题标题】:Proper use of Backbone.js and Marionette to group collections正确使用 Backbone.js 和 Marionette 对集合进行分组
【发布时间】:2014-05-04 18:11:15
【问题描述】:

我不太确定如何使用 Backbone.js 和 Marionette 组织我的收藏和视图。所以我所拥有的是一个相当简单的时间集合(开始、结束、进入)。我想将此集合显示为表格,并在每 4 个条目后重复表格的布局。

Date    Start   End
0   08:00   18:00
1   08:00   18:00
2   08:00   18:00
3   08:00   18:00

Date    Start   End
4   08:00   18:00
5   08:00   18:00
6   08:00   18:00
7   08:00   18:00

Date    Start   End
8   08:00   18:00
9   08:00   18:00

到目前为止,我创建的是一个带有 ItemView 的 CompositeView,但是我不确定如何对集合进行分组和拆分。

这是一个 jsfiddle:http://jsfiddle.net/y799N/1/

HTML:

<script id="row-tmpl" type='text/template'>
    <td><%= date %></td>
    <td><%= start %></td>
    <td><%= end %></td>
</script>

<script id="grid-tmpl" type='text/template'>
        <thead>
            <th>Date</th>
            <th>Start</th>
            <th>End</th>
        </thead>
        <tbody id="bdy"></tbody>
</script>

Javascript:

var Row = Backbone.Marionette.ItemView.extend({
    template: '#row-tmpl',
    tagName: 'tr'
});

var Grid = Backbone.Marionette.CompositeView.extend({
    tagName: 'table',
    template: '#grid-tmpl',
    itemView: Row,

    appendHtml: function(collectionView, itemView){
        collectionView.$('#bdy').append(itemView.el);
    }
});

var Time = Backbone.Model.extend({
    defaults: {
        start : '08:00',
        lazy : '00:45',
        end: '18:00',
        date: 1
    }
});

var TimeCollection = Backbone.Collection.extend({
    model: Time
});

///
var times = new TimeCollection();
for(var i = 0;i<10;i++){
    times.add(new Time({date:i}));
}



var grid = new Grid({
    collection:times
});

grid.render();
console.log(grid.el);
$('#grid').html(grid.el);

【问题讨论】:

  • 这可能对你有帮助backbonejs.org/#FAQ-nested
  • 我根本不会拆分集合,而是为CompositeView 编写一个自定义render 函数。这应该相当简单:遍历集合,追加 ItemView 并使用模运算符有条件地每 x 次插入一行带有标题的行。

标签: javascript jquery backbone.js marionette collectionview


【解决方案1】:

最直接的方法是修改CompositeView 中的appendHtml 函数,以便在需要时插入标题。

appendHtml : function (cv, itemView, index) {
  var $childContainer = this.$(this.itemViewContainer);
  if (index % 4 == 0) {
    $childContainer.append("<tr><td>Date</td><td>Start</td><td>End</td></tr>");
  }
  $childContainer.append(itemView.el);
}

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2020-09-03
    相关资源
    最近更新 更多