Skip to content

Instantly share code, notes, and snippets.

@joaovarandas
Last active August 11, 2016 22:25
Show Gist options
  • Save joaovarandas/3c82aaf051b576d59dbec4afe454f533 to your computer and use it in GitHub Desktop.
Save joaovarandas/3c82aaf051b576d59dbec4afe454f533 to your computer and use it in GitHub Desktop.
LocalStorage JSON Handler
/*
* LocalStorageFactory
* adds support for JSON objects in LocalStorage
*
* @author jvarandas
*/
(function(global) {
var _cache = {}, _ls = {}, ls;
// if localStorage is not available, create a localStorage stub
if (typeof localStorage === 'undefined') {
ls = {
setItem: function(key, value) {
_ls[key] = value;
},
getItem: function(key) {
return _ls[key];
}
}
} else {
ls = localStorage;
}
/**
* Append key/value pair into LocalStorage object
*/
function fnAppender(key, value) {
this.data[key] = value;
return this.data;
}
/**
* Updates LocalStorage with the latest version
*/
function fnSetter() {
ls.setItem(this.key, JSON.stringify(this.data));
}
/**
* LocalStorageFactory
* main-init
*/
function fnFactory(key) {
// we don't want multiple instances of our localStorage object
if (_cache[key]) return _cache[key];
// multi-thread issue
var jsonString = ls.getItem(key);
_cache[key] = jsonString ? JSON.parse(jsonString) : {};
var o = _cache[key];
// end of multi-thread issue
// setup append/set functions in this object
var g = {
"key": key,
"data": o
};
o["set"] = fnSetter.bind(g);
o["append"] = fnAppender.bind(g);
return o;
}
// export LocalStorageFactory to window/global
global["LocalStorageFactory"] = fnFactory;
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment