Best practices for writing apps with Backbone.js

#1 Initial data for app:

Best option is using a server side template, we can simply embed the JSON data needed to populate our initial models right in the page itself.

var appInitialData = {{server_generated_json}};

#2 Rendering tons of models

While rendering with thousands of models and appending them inside container, will huge impcat on performance, may leads to freeze browser.

Use of virtual DOM fragment.

render: function() {
  var container = document.createDocumentFragment();
  // render each subview, appending to our root element
  _.each(this._views, function(subview) {
  //Finally append to actual container


#3 Fixing memory leaks/Zombie Views


// add default close method for views
Backbone.View.prototype.close = function () {
    if (this.onClose) {
// keep a reference to it and close the old
if (!this.listview) {
    this.listview = new MessageListView({ el: $('ul', this.el), model: this.model, collection: this.collection });
else {
    this.listview = new MessageListView({ el: $('ul', this.el), model: this.model, collection: this.collection });



#4 Perform Deep Copies Of Objects

//Underscore dont have a method to make deep copy, so use jquery
var address = $.extend(true, {}, person.address);


#5 Render Parts Of Views Instead Of Entire Views

var mainView = Backbone.View.extend({
    initialize: function(options) {
        this.model.on('change:a', this.renderA, this);
        this.model.on('change:b', this.renderB, this);

    renderA: function() {
        $(‘#a’, this.$el).html(this.model.get(‘a’));
        return this;

    renderB: function() {
        $(‘#b’, this.$el).html(this.model.get(‘b’));
        return this;

    render: function() {


#6 Keep Models Agnostic To Views

#7 Efficient DOM practices using jQuery

Rather than performing large and expensive operations across the entire HTML document, Backbone views provide a $method that performs jQuery operations locally within the view’s container element:

// Append content into the view's container element:
this.$el.append('<li>Hello World</li>');
$(‘ul’, this.$el).append('<li>Hello World</li>');

#8 Use of backbone patterns

backbone patterns by Rico Sta. Cruz

#9 Always return this from render Method

render: function(){
    //DOM rendering
    return this;