Created
April 24, 2015 16:11
-
-
Save cvgellhorn/2c36b7ab440b745d4ec6 to your computer and use it in GitHub Desktop.
JS localStorage handler (requirements: underscore.js)
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
/** | |
* Set and stringify local storage item(s) | |
* | |
* @param {(string|object)} key | |
* @param {*} value | |
*/ | |
window.setStorage = function(key, value) { | |
if (_.isObject(key)) { | |
_.each(key, function(value, key) { | |
localStorage.setItem(key, JSON.stringify(value)); | |
}); | |
} else { | |
localStorage.setItem(key, JSON.stringify(value)); | |
} | |
}; | |
/** | |
* Get and parse local storage item | |
* | |
* @param {string} key | |
* @returns {*} | |
*/ | |
window.getStorage = function(key) { | |
return JSON.parse(localStorage.getItem(key)); | |
}; | |
/** | |
* Remove local storage item(s) | |
* | |
* @param {(string|Array)} key | |
*/ | |
window.removeStorage = function(key) { | |
if (_.isArray(key)) { | |
for (var i = 0, len = key.length; i < len; i++) { | |
localStorage.removeItem(key[i]); | |
} | |
} else { | |
localStorage.removeItem(key); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment