Skip to content

Instantly share code, notes, and snippets.

@miketierney
Last active December 17, 2015 23:28
Show Gist options
  • Save miketierney/5688915 to your computer and use it in GitHub Desktop.
Save miketierney/5688915 to your computer and use it in GitHub Desktop.
An abstraction layer for working with localStorage
/**
* localStorage abstraction
* Get and Set JS Objects in localStorage
*
* 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 () {
var dataStore = function(name){
this.name = name;
};
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