backbone.js - collections and views

Matthew picture Matthew · Apr 13, 2011 · Viewed 19.3k times · Source

I understand how to get a collection together, or an individual model. And I can usually get a model's data to display. But I'm not clear at all how to take a collection and get the list of models within that collection to display.

Am I supposed to iterate over the collection and render each model individually? Is that supposed to be part of the collection's render function?

Or does the collection just have it's own view and somehow I populate the entire collection data into a view?

Just speaking generally, what is the normal method to display a list of models?

Answer

pawlik picture pawlik · Apr 14, 2011

From my experience, it's the best to keep in your collection view references to each model's view.

This snippet from the project I'm currently working on should help you get the idea better:

var MyElementsViewClass = Backbone.View.extend({
    tagName: 'table',

    events: {
        // only whole collection events (like table sorting)
        // each child view has it's own events
    },
    initialize: function() {
        this._MyElementViews = {}; // view chache for further reuse
        _(this).bindAll('add');
        this.collection.bind('add', this.add);
    },
    render: function() {
        // some collection rendering related stuff
        // like appending <table> or <ul> elements

        return this;
    },
    add: function(m) {
        var MyElementView = new MyElementViewClass({
            model: m
        });

        // cache the view
        this._MyElementViews[m.get('id')] = MyElementView;

        // single model rendering
        // like appending <tr> or <li> elements
        MyElementView.render(); 
    }
});

Taking this approach allows you to update views more efficiently (re-rendering one row in the table instead of the whole table).