The goal is to
- make an object that persists upon page reloads,
- have an interface as close as possible to the
Object
class.
function PersistentObject(key,initial_value)
//use for(..in data.keys()) instead of for(..in data)
{
var ret;
if(localStorage[key]) ret=JSON.parse(localStorage[key]);
if(!ret) ret = initial_value;
if(!ret) ret = {};
//JSON.stringify ignores put and keys functions
ret.put=function() { localStorage[key]=JSON.stringify(this) };
ret.keys=function()
{
var res = {};
for(var prop in this) if(this[prop] !== this.put && this[prop] !== this.keys)
res[prop]=true;
return res;
};
return ret;
}
The code is used as follows:
var myPersistentObject = new PersistentObject('myPersistentObject');
var myPersistentArray = new PersistentObject('myPersistentArray',[]);
Unfortunately there is AFAIK no way to get the name of the variable and therefore the name of the variable needs to be passed as first argument.
Also unfortunate is that the function keys
needs to be called in order to iterate over the object. I'm aware of the defineProperty
function that allow to add a propoerty that is not enumerable but AFAIK cross browser compability is an issue with defineProperty
.