CollectionView

Backbone Collections are composed of many models, so when rendering a collection what we need is to render a list of Views:

class CollectionView extends Backbone.View {
  render() {
    // Render a view for each model in the collection
    var html = this.collection.map(model => {
      var view = new this.modelView(model);
      view.render();
      return view.$el;
    });

    // Put the rendered items in the DOM
    this.$el.html(html);
    return this;
  }
}

Note that the modelView property should be a View class; it could be our ModelView class of the previous section or any other view. See how for each model in the collection it instantiates and renders a this.modelView with the current model. As a result, an html variable will contain an array of all rendered views. Finally ...

Get Mastering Backbone.js now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.