I'm really new to web developing and Backbone. I would like some advices for better performance on this program I have written. I tried to write a program similar to these: React vs AngularJS vs KnockoutJS: a Performance Comparison
In particular, I'd like to know if $( "#insideID" ).detach();
is a good strategy or not.
Here is part of my code:
<script id="itemTemplate" type="text/template">
<%= name %>
</script>
$( document ).ready(function() {
// Model
var Item = Backbone.Model.extend({
});
// Collection
var ItemsCollection = Backbone.Collection.extend({
model: Item
});
// View for all elements
var ItemsView = Backbone.View.extend({
className: 'inside',
id: 'insideID',
render: function() {
this.collection.each(function(item) {
var itemView = new ItemView({ model: item });
this.$el.append(itemView.render().el);
}, this);
return this;
}
});
// View for a single element
var ItemView = Backbone.View.extend({
tagName : 'span',
template: _.template($('#itemTemplate').html() ),
render: function() {
this.$el.html( this.template(this.model.toJSON()) );
return this;
}
});
var runBackbone = document.getElementById("run-backbone");
runBackbone.addEventListener("click", function() {
var data = _buildData(); //It returns an array of strings
date = new Date();
$( "#insideID" ).detach();
// It creates the collection
var itemsCollection = new ItemsCollection;
for (var i = 0; i < data.length; i++)
{
newItem = new Item ({name: data[i].label});
itemsCollection.add(newItem);
}
var itemsView = new ItemsView({ collection: itemsCollection });
$("#col-12").append(itemsView.render().el);
runBackbone.innerHTML = (new Date() - date) + " ms";
});
});
In your itemsView render method, instead of appending each itemView to your element, causing many DOM reflows especially if you have many items in your collection, you could use a documentFragment as a container that you append only one time.
render: function() {
this.$el.empty();
var container = document.createDocumentFragment();
this.collection.each(function(item) {
var itemView = new ItemView({ model: item });
container.appendChild(itemView.render().el);
}, this);
this.$el.append(container);
return this;
}
You might want to check out Marionette framework. It will help you if your application starts to get bigger and complex (eg grids, layouts, compositeViews etc), Backbone Marionette
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.