* Backbone localStorage Adapter

(function() {

A simple module to replace Backbone.sync with localStorage-based persistence. Models are given GUIDS, and saved into a JSON object. Simple as that.

Hold reference to Underscore.js and Backbone.js in the closure in order to make things work even if they are removed from the global namespace

var _ = this._;
var Backbone = this.Backbone;

Generate four random hex digits.

function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);

Generate a pseudo-GUID by concatenating random hexadecimal.

function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());

Our Store is represented by a single JS object in localStorage. Create it with a meaningful name, like the name you'd give a table. window.Store is deprectated, use Backbone.LocalStorage instead

Backbone.LocalStorage = window.Store = function(name) { = name;
  var store = this.localStorage().getItem(;
  this.records = (store && store.split(",")) || [];

_.extend(Backbone.LocalStorage.prototype, {

Save the current state of the Store to localStorage.

  save: function() {
    this.localStorage().setItem(, this.records.join(","));

Add a model, giving it a (hopefully)-unique GUID, if it doesn't already have an id of it's own.

  create: function(model) {
    if (! { = guid();
    this.localStorage().setItem("-", JSON.stringify(model));
    return model.toJSON();

Update a model by replacing its copy in

  update: function(model) {
    this.localStorage().setItem("-", JSON.stringify(model));
    if (!_.include(this.records, this.records.push(;;
    return model.toJSON();

Retrieve a model from by id.

  find: function(model) {
    return JSON.parse(this.localStorage().getItem("-";

Return the array of all models currently in storage.

  findAll: function() {
    return _(this.records).chain()
        .map(function(id){return JSON.parse(this.localStorage().getItem("-"+id));}, this)

Delete a model from, returning it.

  destroy: function(model) {
    this.records = _.reject(this.records, function(record_id){return record_id ==;});;
    return model;

  localStorage: function() {
      return localStorage;


localSync delegate to the model or collection's localStorage property, which should be an instance of Store. window.Store.sync and Backbone.localSync is deprectated, use Backbone.LocalStorage.sync instead

Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options, error) {
  var store = model.localStorage || model.collection.localStorage;

Backwards compatibility with Backbone <= 0.3.3

  if (typeof options == 'function') {
    options = {
      success: options,
      error: error

  var resp;

  switch (method) {
    case "read":    resp = != undefined ? store.find(model) : store.findAll(); break;
    case "create":  resp = store.create(model);                            break;
    case "update":  resp = store.update(model);                            break;
    case "delete":  resp = store.destroy(model);                           break;

  if (resp) {
  } else {
    options.error('Record not found.');

Backbone.ajaxSync = Backbone.sync;

Backbone.getSyncMethod = function(model) {
  if(model.localStorage || (model.collection && model.collection.localStorage))
    return Backbone.localSync;

  return Backbone.ajaxSync;

Override 'Backbone.sync' to default to localSync, the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'

Backbone.sync = function(method, model, options, error) {
  return Backbone.getSyncMethod(model).apply(this, [method, model, options, error]);