Skip to content

Instantly share code, notes, and snippets.

@automagisch
Created June 25, 2015 09:54
Show Gist options
  • Save automagisch/fd065c0fea26f094d6c9 to your computer and use it in GitHub Desktop.
Save automagisch/fd065c0fea26f094d6c9 to your computer and use it in GitHub Desktop.
This is a very minimalistic interface on top of the LocalStorage API to save key-value objects as one value to LocalStorage. Done a lot of times, but this one just does the most simplest of things. Quick, easy and safe :)
var LS = function() {
/*
LocalStorageHandler Class
- emulates a more user friendly interface
for the LocalStorage API
*/
var LocalStorageHandler = function() {
this.key = "local";
this.data = {};
this.settings = {
// call prototype.write each time .get or .flush is called
// causing the data store to be saved immediately
autoSave: false
}
// localStorage namespace shortcut
this._ls = window.localStorage;
}
LocalStorageHandler.prototype = {
// initialise LS
init: function() {
var self = this,
revive = function() {
// revives existing localStorage data
var key = self.key,
item = self._ls.getItem(key),
check = new Promise(function(resolve, reject) {
if(item) {
resolve(item);
} else {
reject();
}
});
check.then(function(data) {
// key is existent
// write LS data to self.data as JSON
self.data = JSON.parse(data);
}, function() {
// key is not yet existent
// write data key to LS
self._ls.setItem(key, JSON.stringify(self.data));
});
};
revive();
},
// set local storage keyname
setKey: function(keyName) {
this.key = keyName;
},
// set a key on this store
set: function(key, property) {
this.data[key] = property;
if(this.settings.autoSave) {
this.write();
}
return this.data[key];
},
// get a key from this store
get: function(key) {
return this.data[key];
},
// save this.data stringified to localstorage
write: function() {
this._ls.setItem(this.key, JSON.stringify(this.data));
},
// empty store
flush: function() {
this.data = {};
if(this.settings.autoSave) {
this.write();
}
return this.data;
},
// write a setting to this.settings
setting: function(settingName, settingValue) {
this.settings[settingName] = settingValue;
}
};
return new LocalStorageHandler();
}();
// set the key to work with
LS.setKey("myLocalStorageKey");
// set a setting for lS
LS.setting('autoSave', true);
// this HAS to be called in order to work
LS.init();
// from this point, LS can be accessed and the methods get, set, write and flush
// will perform actions on localStorage.myLocalStorageKey
// LS.set('firstname', 'Koen')
// LS.get('firstname') => Koen
// LS.set('firstname', 'Job')
// LS.get('firstname') => Job
// LS.flush();
// LS.get('firstname') => undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment