Created
September 6, 2013 06:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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