Blog based on Backbone.js

We turn the example mvcBackboneBlog into a standalone web application that doesn't require a server. We store the posts locally in the browser using the localStorage.

We use the extension Backbone.localStorage that provides an adapter for storing models and collections on the localStorage. The extension replaces the Backbone.sync() method and no other changes are required to the models and collections.

First we must include the backbone.localstorage.js script in the HTML header

views/layout.haml
!!! 5
%html
  %head
    %meta(charset="utf-8")
    %meta(content="IE=edge,chrome=1" http-equiv="X-UA-Compatible")
    %meta(name="viewport" content="width=device-width, user-scalable=0, initial-scale=1.0, maximum-scale=1.0;")
    %link(rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css")
    %script(type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js")
    %script(type="text/javascript" src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js")
    %script(type="text/javascript" src="handlebars-1.0.rc.1.js")
    %script(type="text/javascript" src="underscore.js")
    %script(type="text/javascript" src="json2.js")
    %script(type="text/javascript" src="backbone.js")
    %script(type="text/javascript" src="backbone.localStorage.js")
  
    %title
      Blog
    ...

The second step is to instruct Backbone to store the Articles collection in the localStorage. This is achieved by removing the url attribute in the collection and adding the localStorage as below:

views/layout.haml
  var Article = Backbone.Model.extend ({
  });

  var Articles = Backbone.Collection.extend ({
    model: Article,
    localStorage: new Backbone.LocalStorage("Articles")
  });


This example doesn't require a server but it requires Sinatra for generating the main page (index.html). This can be achieved by starting the Sinatra server with the following command:

terminal
ruby server.rb

You can save the index.html page by visiting the URL http://localhost:4567 in your browser or on Unix systems you can just execute the following command:

terminal
wget localhost:4567

If you want to deploy the web app as a standalone application you must also copy the content of the /public directory at the same location of the index.html file.

You can try the try the web app also by following the "Try it" link on the top right.