Skip to content

Instantly share code, notes, and snippets.

@rpocklin
Created September 6, 2013 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpocklin/6460255 to your computer and use it in GitHub Desktop.
Save rpocklin/6460255 to your computer and use it in GitHub Desktop.
Backbone model using localstorage as an auxiliary storage mechanism (giving you session-esque properties in the frontend). Uses Require.js, just strip if back if you don't use it. Recommendation is to call loadFromStorage() in initialize() method and call saveToStorage() when the model changes.
define(['backbone'],
function(Backbone) {
return Backbone.Model.extend({
_storage: localStorage || {setItem: function() {}, getItem: function() {return {};}},
saveToStorage: function() {
this._storage.setItem(this._getKey(), JSON.stringify(this.toJSON()));
},
loadFromStorage: function() {
var value = this._storage.getItem(this._getKey());
return value && JSON.parse(value);
},
_getKey: function() {
if (!this._storageKey) {
throw new Error("Key not defined for local storage model.");
}
return this._storageKey;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment