Last active
May 30, 2016 08:50
-
-
Save danb-humaan/b5175ac4d82fd7a948b8 to your computer and use it in GitHub Desktop.
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
/** | |
* Saves an item in localStorage so it can be retrieved later. This method automatically encodes the value as JSON, so you don't have to. If you don't supply a value, this method will return false immediately. | |
* | |
* @example <caption>set localStorage that persists until it is manually removed</caption> | |
* LocalStorage.setItem('key', 'value'); | |
* | |
* @example <caption>set localStorage that persists for the next 30 seconds before being busted</caption> | |
* LocalStorage.setItem('key', 'value', 30); | |
* | |
* @kind function | |
* @function LocalStorage#setItem | |
* | |
* @param {!string} key - Name of the key in localStorage. | |
* @param {!*} value - Value that should be stored in localStorage. Must be able to be encoded/decoded as JSON. Please ensure your object doesn't have the key __expiry as this will accidentally conflict with the expiry handler. | |
* @param {?int} [expiry=null] - Time in seconds that the localStorage cache should be considered valid. | |
* @returns {boolean} Returns true if it was stored in localStorage, false otherwise. | |
*/ | |
setItem: function (key, value, expiry) { | |
if (!this.supportsLocalStorage() || typeof value === 'undefined' || key === null || value === null) { | |
return false; | |
} | |
if (typeof expiry === 'number') { | |
value = { | |
__data: value, | |
__expiry: Date.now() + (parseInt(expiry) * 1000) | |
}; | |
} | |
try { | |
localStorage.setItem(key, JSON.stringify(value)); | |
return true; | |
} catch (e) { | |
console.log('Unable to store ' + key + ' in localStorage due to ' + e.name); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment