Last active
August 29, 2015 13:57
-
-
Save jefsnare/9539093 to your computer and use it in GitHub Desktop.
JG_LocalStorage helper methods for javascript 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
/** | |
* Various localStorage method helpers for setting, | |
* getting and checking localStorage data. | |
*/ | |
JG_LocalStorage = (function () { | |
'use strict'; | |
return { | |
/* add data to localStorage */ | |
set: function (key, value) { | |
/* if the value is an object, stringify it to save it in localStorage */ | |
if (typeof value === 'object') { | |
value = JSON.stringify(value); | |
} | |
localStorage.setItem(key, value); | |
}, | |
/* retrieve data from localStorage object */ | |
get: function (key) { | |
var data; | |
if (!this.hasData(key)) { | |
return false; | |
} | |
data = localStorage[key]; | |
/* if the data is JSON, try to parse */ | |
try { | |
return JSON.parse(data); | |
} catch (e) { | |
return data; | |
} | |
}, | |
/* check if the item exists and it has data */ | |
hasData: function (key) { | |
return !!localStorage[key] && !!localStorage[key].length; | |
} | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment