Search code examples
backbone.jsmarionette

How to render Marionette 3 CollectionView into a table column?


I'm currently working on a legacy program with symfony 1.4 and a bunch of outdated technologies. Recently we decided to add Backbone/Marionette to project in order to make things a bit easier.

The problem I'm facing is rendering a collection view into a table column. The table already exists and is functional with more than 2k LOC behind it, which makes it impossible for me to rewrite it ATM.

<table>
<thead>
<tr>
    <th>Item</th>
    <th>Quantity</th>
    <th>Price</th>
    <th>...</th>
    <th></th> <!-- This is the column -->
    <th>Total price</th>
</tr>
</thead>
<tbody>
    ...
</tbody>
</table>

All other columns, except the one specified by comment, are already rendered into the page. I've followed the documentations to Marionette attachHtml and attachBuffer but couldn't implement a working solution.


Solution

  • https://jsfiddle.net/cbzs67ar/

    var collection = new Backbone.Collection([
      { id: 1, text: 'one' },
      { id: 2, text: 'two' },
      { id: 3, text: 'three' },
      { id: 4, text: 'four' },
      { id: 5, text: 'five' },
      { id: 6, text: 'six' },
      { id: 7, text: 'seven' }
    ])
    
    var MyChildView = Mn.View.extend({
      initialize() {
        this.render();
      },
      template: _.template(': <%- text %>')
    });
    var CollectionView = Mn.CollectionView.extend({
      el: '.tbody-hook',
      childView: MyChildView,
      buildChildView(model, ChildView) {
        var view = new ChildView({
          el: '.td-' + model.id,
          model: model
        }); 
        return view;
      },
      attachHtml: _.noop,
      attachBuffer: _.noop
    });
    
    var myRegion = new Marionette.Region({ el: '#some-region' });
    
    myRegion.show(new CollectionView({ collection: collection }));
    

    Use a collectionview to manage the pre-rendered child by a column selector. You'll need to disable the collectionview from attaching the children to it's own container and you'll need to force the children to render themselves after they're instantiated.