Created
October 13, 2015 19:28
-
-
Save andeersg/b317b976f801d3103686 to your computer and use it in GitHub Desktop.
Simple JavaScript object for saving and restoring localStorage items.
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
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