I’d like to create a Javascript object that can save and load its state (to local storage).
This is the basic pattern I’m using:
var obj = function () {
// private members
//
return {
// public members
load: function () {
this.state = JSON.parse(localStorage.getItem('obj'));
if (this.state === null) {
this.state = {
name: 'foo'
};
}
},
save: function () {
localStorage.setItem('obj', JSON.stringify(this.state));
}
};
}();
// load state
obj.load();
console.log(obj.state.name);
// save state
obj.state.name = 'bar';
obj.save();
But there’s one thing that annoys me about this pattern: I have to access the object’s persistent properties through the ‘state’ property.
How can I rewrite this so I can use the object in a more natural way, like:
// load state
obj.load();
console.log(obj.name);
// save state
obj.name = 'bar';
obj.save();
This is a very simple ‘state’, but the solution has to work for a complex state object with nested objects, arrays etc., so simply adding a ‘name’ property to my object is not what I’m after.
If you don’t care which properties get loaded/saved then you can simply copy all from state into self. For example, after reading into
var state(instead ofthis.statesince you don’t wantstateto be a part ofthisanymore):for(x in state) this[x] = state[x];similarly, you’d save out:
var state = {}; for(x in this) state[x] = this[x]However, if you want to have a pre-defined list, then I’d recommend:
var fields = ['name', 'zip', 'age'];And then use
for(x in fields) this[x] = state[x]to load andfor(x in fields) state[x] = this[x];to save.Sorry it’s a bit pieced together, but I hope you can follow what I mean 🙂
EDIT: Added full example per OPs request.
An example of a full solution using this technique is as follows: