Skip to content

Instantly share code, notes, and snippets.

@andeersg
Created October 13, 2015 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andeersg/b317b976f801d3103686 to your computer and use it in GitHub Desktop.
Save andeersg/b317b976f801d3103686 to your computer and use it in GitHub Desktop.
Simple JavaScript object for saving and restoring localStorage items.
var StorageUnit = (function() {
var is_supported = function() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch (e) {
return false;
}
};
var _ = window.StorageUnit = {
supported: is_supported(),
save: function(key, data) {
if (!_.supported) { return; }
var toSave = {
data: data
}
toSave = JSON.stringify(toSave);
localStorage['StorageUnit_' + key] = toSave;
},
get: function(key) {
if (!_.supported) { return; }
if (typeof localStorage['StorageUnit_' + key] !== 'undefined') {
var restoredData = JSON.parse(localStorage['StorageUnit_' + key]);
return restoredData.data;
}
},
remove: function(key) {
if (!_.supported) { return; }
localStorage.removeItem('StorageUnit_' + key);
}
};
return window.StorageUnit;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment