Created
May 22, 2014 11:56
-
-
Save MoOx/64a7d0838b34c3ac09c4 to your computer and use it in GitHub Desktop.
Simple localStorage abstraction
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
var prefix = "storage." | |
, storage = { | |
getAll: function() { | |
var data = {}; | |
for (var key in localStorage){ | |
if (key.indexOf(prefix) === 0) { | |
data[key.replace(prefix, "")] = storage.getFromLocalStorage(key); | |
} | |
} | |
return data; | |
} | |
, getFromLocalStorage: function(key) { | |
var value = localStorage.getItem(key); | |
try { | |
value = JSON.parse(value); | |
} | |
catch (e) { | |
// if (console) console.log(key + " doesnt seems to be JSON"); | |
} | |
return value; | |
} | |
// Get item from localStorage | |
, get: function(key, defaultValue) { | |
return storage.getFromLocalStorage(prefix + key) || defaultValue; | |
} | |
// Set item in localStorage | |
, set: function(key, value) { | |
if (typeof value === "object") { | |
value = JSON.stringify(value); | |
} | |
localStorage.setItem(prefix + key, value); | |
} | |
, remove: function(key) { | |
localStorage.removeItem(prefix + key); | |
} | |
} | |
module.exports = storage |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment