/* Implementation of localStorage object. See also: * https://developer.mozilla.org/en/DOM/Storage#localStorage * http://dev.w3.org/html5/webstorage/ */ (function(global) { // Internal data storage var data = Object.create(null); // Later, local gets exposed as .localStorage var local = Object.create(data); // a reliable way to determine the type of a value or object var getType = function(val) { if (val===global) return "global"; return ({}).toString.call(val).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); } // Make sure the data being stored -- throw a descriptive error if not var checkVal = function(key,val,path,depth) { depth = depth || 0; // we will limit recusion depth to 10 levels (should be more than enough) if (depth>9) { throw new Error("ERROR: localStorage '"+key+"' is nested too deep at "+path); } switch (getType(val)) { // recursively check object properties case "object": { path = path || ""; var props = Object.keys(val); // array of object property names (excludes stuff on proto chain) for (var i=0; i= keys.length) ? null : data[keys[idx]]; } addProp("key",fKey); // get specific item by it's key var fGetItem = function(key) { return (key in data) ? data[key] : null; } addProp("getItem",fGetItem); // remove item with given key var fRemoveItem = function(key) { delete data[key]; } addProp("removeItem",fRemoveItem); // clear all data var fClear = function() { var keys = Object.keys(data); // array of stored property names while (keys.length) delete data[keys.pop()]; // delete each key } addProp("clear",fClear); // get the localStorge data in JSON format var fToJSON = function() { return JSON.stringify(data); } addProp("toJSON",fToJSON); // set the localStorage data from supplied JSON string var fFromJSON = function(str) { var newData = JSON.parse(str); for (i in newData) data[i] = newData[i]; } addProp("fromJSON",fFromJSON); // now expose the localStorage object to JS environment addProp("localStorage",local); })(this);