将一个HTML表的元素指定为Marionette for Backbone.js中的一个区域

时间:2012-08-20 18:37:27

标签: javascript backbone.js marionette

问题

使用Backbone.Marrionette.Layout来呈现一些表格数据。该表的<tbody>部分是Backbone.Marionette.Region,用于显示Backbone.Marionette.CollectionView

我无法弄清楚如何使用Marionette的“Regions”来解决这个问题,而不会通过在<tbody>元素中插入额外的HTML元素来搞乱表格显示。

示例代码

Layout看起来像这样:

Backbone.Marionette.Layout.extend({
    template:...
    regions:{
        list_region: '#list-region'
    }
    onRender:function(){
        var collection = new TheCollection()
        var collectionView = new TheCollectionView({
            collection: collection
        })
        // PROBLEM: The region seems to needs its own HTML element,
        //   and the CollectionView also seems to need its on HTML
        //   element, but as far as I can see, there is only room 
        //    for one element: <tbody>?
        this.list_region.show(collectionView);
});

布局的模板包含整个表格:

<table>

    <tbody id='list-region'>

    </tbody>

    <tfoot id='footer-region'>
        Some other stuff goes here that is not a collection, so I was able 
        to make the View's 'tagName' property 'tr', which worked fine.
    </tfoot>

</table>

有什么建议吗?

2 个答案:

答案 0 :(得分:16)

此布局的目的仅仅是为了方便桌子吗?如果是这样,您应该考虑使用CompositeView。


RowView = Marionette.ItemView.extend({
  tagName: "tr",
  template: ...
});

TableView = Marionette.CompositeView.extend({
  template: ...,

  childView: RowView,

  childViewContainer: "#list-region"
});

这就是它。这会将所有itemView渲染到tbody。

答案 1 :(得分:2)

Marionette 3弃用了CompositeView类。相反,一个区域现在可以使用所呈现的内容覆盖其el 内部视图与new replaceElement option

请参阅this example以呈现表格:

var RowView = Marionette.View.extend({
  tagName: 'tr',
  template: '#row-template'
});

var TableBody = Marionette.CollectionView.extend({
  tagName: 'tbody',
  childView: RowView
});

var TableView = Marionette.View.extend({
  tagName: 'table',
  className: 'table table-hover',
  template: '#table',

  regions: {
    body: {
      el: 'tbody',
      replaceElement: true
    }
  },

  onRender: function() {
    this.showChildView('body', new TableBody({
      collection: this.collection
    }));
  }
});

var list = new Backbone.Collection([
  {id: 1, text: 'My text'},
  {id: 2, text: 'Another Item'}
]);

var myTable = new TableView({
  collection: list
});

myTable.render();