Backbone collection rendering sample
by niki4810
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script>
<script type="text/template" id="list-item">
<li><%= title %></li>
</script>
<script type="text/template" id="list-collection">
<h1>My List</h1>
<hr/>
<ul class="list"></ul>
</script>
<button id="btnFast">Generate List: fast</button>
<button id="btnSlow">Generate List:slow</button>
JavaScript
var MyApp = {};
MyApp.ListItem = Backbone.View.extend({
_template: _.template($('#list-item').html()),
render: function () {
this.$el.html(this._template(this.model.toJSON()));
return this;
}
});
MyApp.ListCollection = Backbone.View.extend({
_template: _.template($('#list-collection').html()),
render: function () {
this.$el.html(this._template(this.model.toJSON()));
return this;
},
slowLoad : function(data){
var collection = new Backbone.Collection(data);
var self = this;
collection.each(function (model) {
var liView = new MyApp.ListItem({
model: model
});
self.$el.append(liView.render().el);
});
},
fastLoad: function (data) {
var collection = new Backbone.Collection(data);
var self = this;
var container = document.createDocumentFragment();
collection.each(function (model) {
var liView = new MyApp.ListItem({
model: model
});
container.appendChild(liView.render().el)
});
this.$el.append(container);
}
});
$(function () {
var data = [];
for (var i = 0; i < 10000; i++) {
data.push({
title: "abc" + i
});
};
var liCollection = new MyApp.ListCollection({
model: new Backbone.Model()
});
liCollection.render().$el.appendTo('body');
$("#btnFast").click(function () {
liCollection.fastLoad(data);
});
$("#btnSlow").click(function () {
liCollection.slowLoad(data);
});
});