Full template rendering
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>Row</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<% _(children).each(function(model) { %>
<tr id='<%= model.cid %>'>
<td><%= model.row %></td>
<td><%= model.name %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
<div id='view'></div>
JavaScript
var ItemView, ListView, i, data, view;
ItemView = Backbone.View.extend({
events: {
"click td": "show"
},
show: function () {
console.log(this.model.get("name"));
}
});
ListView = Backbone.View.extend({
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
});
$table = $(html);
this.collection.each(function (model) {
var subview = new ItemView({
el: $table.find("#" + model.cid),
model: model
});
});
this.$el.empty();
this.$el.append($table);
return this;
}
});
data = [];
for (i = 0; i < 100; i = i + 1) {
data.push({
row: i,
name: "Row " + i
});
}
view = new ListView({
template: _.template($('#tpl-table').html()),
collection: new Backbone.Collection(data),
el: '#view'
});
view.render();