Skip to content

Instantly share code, notes, and snippets.

@Cifro
Last active December 17, 2015 00:39
Show Gist options
  • Save Cifro/5522330 to your computer and use it in GitHub Desktop.
Save Cifro/5522330 to your computer and use it in GitHub Desktop.
Simple wrapper for localStorage, needs underscore.js
// needs underscore.js
Storage = function(key, defaults)
{
this.key = key;
this.defaults = defaults;
this.data = {};
};
Storage.prototype.load = function(what)
{
if(typeof(localStorage) != 'undefined'){
var s = localStorage.getItem(this.key);
if(s !== null){
try{
this.data = JSON.parse(s);
this.data = _.defaults(this.data, this.defaults);
}catch(e){
this.data = s;
}
if(typeof what !== "undefined" && (typeof this.data === "object"))
return this.data[what];
else
return this.data;
}else{
return this.defaults;
}
}
return null;
};
Storage.prototype.save = function(data)
{
if(typeof(localStorage) != 'undefined'){
if(typeof data === "string"){
localStorage.setItem(this.key, data);
}else if(typeof data === "object"){
data = _.defaults(data, this.defaults);
localStorage.setItem(this.key, JSON.stringify(data));
}
}
return data;
};
// Usage
var storage = new Storage('app-settings-or-something', {activeTab: '', url: 'http://localhost'});
storage.save({activeTab: '#theme-settings'});
storage.load(); // {activeTab: '#theme-settings', url: 'http://localhost'}
storage.load('activeTab'); // #theme-settings
var storage2 = new Storage('simple-string', '#my-element-id');
storage2.save('#my-another-element-id');
storage2.load(); // #my-another-element-id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment