Just a quick and simple class for working with `localStorage`! Extremely easy to use!
Easy Uses!
Simply assign:
var lsh = new localStorageHelper()
And go!
- lsh.isAvailable; // after class called, becomes boolean property
- lsh.get(); // retrieve an Object of ALL available localStorage items
- lsh.get('keyName'); // retrieve value for storage item having passed key name
- lsh.set('keyName', 'assorted value'); // value can be ALMOST anything!
- lsh.remove('keyName'); // seeks to remove storage item having key name
- lsh.clear(); // remove ALL storage items
- lsh.on('eventName', callback); // set a callback method to preform when event is fired
- lsh.off('eventName', callback); // attempts to remove callback from list of handlers on given event
Oh, and did I mention events?!
- lsh.on('get', function(e) { /* e={ eventType: "get", key: "keyName", url: "currentAddress", value: "the value" } */ }); // do work whenever get is called AND something is actually retrieved
- lsh.on('set', function(e) { /* e={ eventType: "set", key: "keyName", success: bool, url: "currentAddress", value: "the value" } */ }); // do work when new value is set
- lsh.on('remove', function(e) { /* e={ eventType: "remove", key: "keyName", success: bool, url: "currentAddress", value: "the value" } */ }); // do work when value is removed
- lsh.on('clear', function(e) { /* e={ eventType: "clear", success: bool, url: "currentAddress" } */ }); // do work when all values are cleared
Code
function localStorageHelper() {
// variable for this class
var $this = this;
// set whether if localstorage is isAvailable
this.isAvailable = function() {
try { return 'localStorage' in window && window['localStorage'] !== null; }
catch (e) { return !1 }
}();
// HELPERS
this.keyExists = function(key) { return this.isAvailable && key !== void 0 && localStorage.key(key); }
this.keyAtIndex = function(i) { return this.isAvailable ? localStorage.key(i) : void 0; }
// returns an array of keys
this.getKeys = function() {
if (!this.isAvailable) return void 0;
var k = [];
for (var i=0;i<localStorage.length;i++) k.push(localStorage.key(i));
return k;
}
// returns array of values
this.getValues = function() {
if (!this.isAvailable) return void 0;
var v = [];
for (var i=0;i<localStorage.length;i++) v.push(this.get(localStorage.key(i)));
return v;
}
// get/set/remove/clear local storage item(s) and fire get event
this.get = function(key) {
if (this.isAvailable) {
if (typeof key === "number") key = this.keyAtIndex(key);
if (this.keyExists(key)) {
var val;
try { return val = JSON.parse(localStorage.getItem(key)); }
catch(err) { return val = localStorage.getItem(key); }
finally { this.onGet.fire(key, val); }
}
else if (key === void 0) { // if no key provided, then assume "get all" and return Object of all items in localStorage
var a = {};
try {
for (var i=0;i<localStorage.length;i++) if (this.keyAtIndex(i)) a[this.keyAtIndex(i)] = this.get(this.keyAtIndex(i));
return a;
}
finally { this.onGet.fire(key, a); }
}
}
return void 0;
}
this.set = function(key, value) {
if (this.isAvailable) this.onSet.fire(key, value, function() {
try {
try { localStorage.setItem(key, JSON.stringify(value)); }
catch(err) { localStorage.setItem(key, value); }
return true;
}
catch(err) {}
return false;
}());
return $this;
}
this.remove = function(key) {
if (this.isAvailable && this.keyExists(key)) this.onRemove.fire(key, this.get(key), function() {
try { localStorage.removeItem(key); return true; }
catch(err) { return false; }
}());
return $this;
}
this.clear = function() {
if (this.isAvailable) this.onClear.fire(null, null, function() {
try { localStorage.clear(); return true; }
catch(err) { return false; }
}());
return $this;
}
// EVENTS
function setEvent(eType) {
var eventName = "on" + (eType.charAt(0).toUpperCase() + eType.slice(1)),
ret = function(handler) {
if (typeof handler == "function") {
var $handlers = this[eventName].handlers,
strHandler = handler.toString().replace(/ |\t|\r|\n/ig, '');
for (var x in $handlers) if (strHandler == $handlers[x].toString().replace(/ |\t|\r|\n/ig, '')) return this[eventName];
$handlers.push(handler);
}
return this[eventName];
}
ret.fire = function(k, v, s) {
var $handlers = this.handlers,
args = { eventType: eType };
if (k !== undefined && k !== null) args.key = k
if (v !== undefined && v !== null) args.value = v
if (s !== undefined && s !== null) args.success = s
args.url = window.location.toString();
for (var x in $handlers) $handlers[x].apply($this, [args])
}
ret.handlers = [];
return ret;
}
this.on = function(a, b) {
a = "on" + (a.charAt(0).toUpperCase() + a.slice(1));
this.hasOwnProperty(a) && this[a].apply($this, [b]);
};
this.off = function(a, b) {
a = "on" + (a.charAt(0).toUpperCase() + a.slice(1));
if (this.hasOwnProperty(a) && "function" == typeof b) {
var c = this[a].handlers,
e = b.toString().replace(/ |\t|\r|\n/ig, ""),
d;
for (d in c)
if (e == c[d].toString().replace(/ |\t|\r|\n/ig, "")) {
c.splice(d, 1);
break;
}
}
return $this;
};
this.onGet = setEvent.apply(this, ['get']);
this.onSet = setEvent.apply(this, ['set']);
this.onRemove = setEvent.apply(this, ['remove']);
this.onClear = setEvent.apply(this, ['clear']);
// Final summary, check if LS is even available, if not, throw error and process callback method if provided
if (!this.isAvailable) {
var msg = "[localStorage] is unavailble!";
if (arguments.length && typeof arguments[0] == "function") arguments[0].apply($this, [{ isAvailable: this.isAvailable, Error: msg }]);
throw new Error(msg);
}
return this;
}
Go play with it here!