Backbone: Views list rendering performance
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<!-- Put HTML into HTML -->
<table id="foobar">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody></tbody>
</table>
JavaScript
var Person = Backbone.Model.extend();
var PersonCollection = Backbone.Collection.extend({
model: Person
});
var TableView = Backbone.View.extend({
render: function () {
//set array of our sub views
this.rowViews = this.model.get('people')
.map(function (model, index, collection) {
return new TableRowView({
model: model
});
});
//Push to DOM only once
this.$('tbody').html(
//simply walkt through plain Array
_.reduce(
//of rendered jQuery nodes
_.invoke(this.rowViews,"render"),
//to merge it into one set
jQuery.merge
)
);
//return somethin, it's often useful
return this.$el;
}
});
var TableRowView = Backbone.View.extend({
render: function () {
this.$el.data('id', this.model.id)
.append($('<td />').text(this.model.get('firstName')))
.append($('<td />').text(this.model.get('lastName')));
return this.$el;
},
});
var tableView = new TableView({
el: $('#foobar'),
model: new Backbone.Model({
people: new PersonCollection([{
id: 1,
firstName: 'Bill',
lastName: 'Clinton'
}, {
id: 2,
firstName: 'Geroge',
lastName: 'Bush'
}, {
id: 3,
firstName: 'Barack',
lastName: 'Obama'
}])
})
});
tableView.render();