Last active
December 17, 2015 23:28
-
-
Save miketierney/5688915 to your computer and use it in GitHub Desktop.
An abstraction layer for working with localStorage
This file contains 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
/** | |
* localStorage abstraction | |
* Get and Set JS Objects in localStorage | |
* | |
* This is meant for really simple localStorage needs, not to replace | |
* anything like Backbone.localStorage that's more robust. A good | |
* use-case is storing an array of IDs for models that are stored on | |
* the server. | |
* | |
* Usage: | |
* | |
* var myStore = new dataStore('storageName'); | |
* // >> dataStore {name: "storageName", fetch: function, set: function} | |
* myStore.set({someKey : "This will be stored as JSON"}); | |
* // >> undefined | |
* myStore.fetch(); | |
* // >> Object {someKey : "This will be stored as JSON"} | |
* localStorage.getItem('storageName'); | |
* // >> "{"someKey":"This will be stored as JSON"}" | |
* | |
*/ | |
var DataStore = (function () { | |
/** | |
* Constructor. Takes a name and optional second value, which will be set in | |
* to the data store using the `set` method. | |
* | |
* @param name {String} string to use as the key for storing the data in | |
* localStorage | |
* @param data (optional) can be any valid JavaScript object, will get stored | |
* in the `name`d location in localStorage | |
**/ | |
var dataStore = function(name){ | |
this.name = name; | |
if (data) { this.set(data); } | |
}; | |
dataStore.prototype = { | |
/** | |
* Getter method; retrieves the data stored under the dataStore's name from | |
* localStorage, then parses it with JSON.parse | |
* | |
* @method fetch | |
* @param none | |
* @returns object | |
**/ | |
fetch : function () { | |
return JSON.parse(localStorage.getItem(this.name)); | |
}, | |
/** | |
* Setter method; takes a JavaScript object, runs it through JSON | |
* stringify, and then stores it in localStorage under the dataStore's name | |
* | |
* @method set | |
* @param obj {Object} Can be any valid JavaScript object -- whether that's an object or a string. Should be something that can be parsed by JSON.stringify | |
* @returns undefined | |
**/ | |
set : function (obj) { | |
localStorage.setItem(this.name, JSON.stringify(obj)); | |
} | |
}; | |
return dataStore; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment