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 the html
array can be attached easily to the $el
element.
For an example of how to use CollectionView
, see the following example:
class MyModelView extends ModelView { // … ) class MyView extends...