public
Last active

Backbone sessionStorage Adapter

  • Download Gist
backbone.sessionStorage.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
/**
* Backbone sessionStorage Adapter
* Based on https://github.com/jeromegn/Backbone.localStorage
*/
 
(function() {
// A simple module to replace `Backbone.sync` with *sessionStorage*-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 *sessionStorage*. Create it
// with a meaningful name, like the name you'd give a table.
// window.Store is deprectated, use Backbone.SessionStorage instead
Backbone.SessionStorage = window.Store = function(name) {
this.name = name;
var store = this.sessionStorage().getItem(this.name);
this.records = (store && store.split(",")) || [];
};
 
_.extend(Backbone.SessionStorage.prototype, {
 
// Save the current state of the **Store** to *sessionStorage*.
save: function() {
this.sessionStorage().setItem(this.name, 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 (!model.id) {
model.id = guid();
model.set(model.idAttribute, model.id);
}
this.sessionStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
this.records.push(model.id.toString());
this.save();
return model.toJSON();
},
 
// Update a model by replacing its copy in `this.data`.
update: function(model) {
this.sessionStorage().setItem(this.name+"-"+model.id, JSON.stringify(model));
if (!_.include(this.records, model.id.toString())) this.records.push(model.id.toString()); this.save();
return model.toJSON();
},
 
// Retrieve a model from `this.data` by id.
find: function(model) {
var stored = this.sessionStorage().getItem(this.name+"-"+model.id);
if(stored) {
return JSON.parse(stored);
} else {
return null;
}
},
 
// Return the array of all models currently in storage.
findAll: function() {
return _(this.records).chain()
.map(function(id){return JSON.parse(this.sessionStorage().getItem(this.name+"-"+id));}, this)
.compact()
.value();
},
 
// Delete a model from `this.data`, returning it.
destroy: function(model) {
this.sessionStorage().removeItem(this.name+"-"+model.id);
this.records = _.reject(this.records, function(record_id){return record_id == model.id.toString();});
this.save();
return model;
},
 
sessionStorage: function() {
return sessionStorage;
}
 
});
 
// sessionSync delegate to the model or collection's
// *sessionStorage* property, which should be an instance of `Store`.
// window.Store.sync and Backbone.sessionSync is deprectated, use Backbone.SessionStorage.sync instead
Backbone.SessionStorage.sync = function(method, model, options, error) {
var store = model.sessionStorage || model.collection.sessionStorage;
 
// Backwards compatibility with Backbone <= 0.3.3
if (typeof options == 'function') {
options = {
success: options,
error: error
};
}
 
var resp, syncDfd = $.Deferred();
 
switch (method) {
case "read": resp = model.id != 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) {
options.success(resp);
syncDfd.resolve();
} else {
if(options.error) {
options.error("Record not found");
}
syncDfd.reject();
}
 
return syncDfd.promise();
};
 
Backbone.SessionStorage.ajaxSync = Backbone.sync;
Backbone.sessionStorageEnabled = true;
 
Backbone.bypassSessionStorage = function(obj, func, options) {
Backbone.sessionStorageEnabled = false;
var result = func.call(obj, options || {});
Backbone.sessionStorageEnabled = true;
return result;
}
 
Backbone.getSyncMethod = function(model) {
if((model.sessionStorage || (model.collection && model.collection.sessionStorage)) && Backbone.sessionStorageEnabled)
{
return Backbone.SessionStorage.sync;
}
 
return Backbone.SessionStorage.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]);
};
 
})();

Updated to work with Backbone 1.0 (and dropped backwards compatibility with ancient versions).

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.