Columns as views

by nikoshr

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://backbonejs.org/backbone-min.js"></script>
<script id="tpl-table" type="text/template">
    <table>
        <thead>
            <tr>
                <th></th>
                <% _(children).each(function(model) { %>
                	<th><%= model.id %></th>                
                <% }); %>
            </tr>
        </thead>
        <tbody>
        <% _(properties).each(function(prop) { %>
            <tr>
                <td><%= prop %></td>
                <% _(children).each(function(model) { %>
                	<td class="<%= model.cid %>"><% print(model[prop]); %></td>
                <% }); %>
            </tr>
        <% }); %>
        </tbody>
     </table>
</script>

Click on a cell
<div id='view'></div>
<div id='log'></div>

CSS

td {border: 1px solid #000; padding:2px 5px;}
td.selected {background: red}

JavaScript

var ItemView, ListView, i, data, view;

ItemView = Backbone.View.extend({
    events: {
        "click ": "show"
    },
    show: function () {
        this.$el.toggleClass('selected');
        $('#log').append('<p>Clicked model '+this.model.get('id')+'</p>');
    }
});

ListView = Backbone.View.extend({
    initialize: function(opts) {
        this.options = opts;
    },
    render: function () {
        var data, html, $table, template = this.options.template;

        data = this.collection.map(function (model) {
            return _.extend(model.toJSON(), {
                cid: model.cid
            });
        });

        html = this.options.template({
            children: data,
            properties: ['id', 'name']
        });

        $table = $(html);
        
        this.collection.each(function (model, ix) {
            var $el = $table.find("." + model.cid),
            	subview = new ItemView({
                el: $el,
                model: model
            });
        });

        this.$el.empty();
        this.$el.append($table);

        return this;
    }
});


data = [];
for (i = 1; i <= 10; i++) {
    data.push({
        id: i,
        name: "M " + i
    });
}

view = new ListView({
    template: _.template($('#tpl-table').html()),
    collection: new Backbone.Collection(data),
    el: '#view'
});
view.render();