Marionette.js. CollectionView. Build Tables Using Marionette 3

Marionette 3 doesn't use `CompositeView` any more. We now build tables using `View`s and `regions`.

by marionettejs

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.radio/2.0.0/backbone.radio.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/3.0.0/backbone.marionette.js"></script>
<div id="region"></div>

<script id="table" type="x-template/underscore">
<thead>
  <tr>
    <th>ID</th>
    <th>Body</th>
  </tr>
</thead>
<tbody></tbody>
</script>

<script id="row-template" type="x-template/underscore">
<td><%- id %></td>
<td><%- text %></td>
</script>

JavaScript

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

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

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

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

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

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

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

const myApp = new Marionette.Application({
  region: '#region'
});

myApp.showView(myTable);