I'm trying out HTML5 LocalStorage.
In the examples I only see simple JSON data-objects, but I have some custom data-object classes with various methods added (like addChild, cleanup, etc).
Is it possible to store instances of these custom objects directly in LocalStorage, or do I understand the whole concept of LocalStorage totally wrong then?
localStorage can only store strings, so anything you try to store in localStorage will be serialized to a string first. As such it doesn't make sense to store definitions in localStorage, just data. You can create a method that generates a custom object instance from serialized data:
function Custom() {}
Custom.prototype.addChild = function () {
console.log(this.x, this.y);
}
// LocalStorage serializes to String first
Custom.prototype.toString = function () {
return JSON.stringify({
"x": this.x,
"y": this.y,
});
};
Custom.unserialize = function (customData) {
customData = JSON.parse(customData);
var custom = new Custom;
custom.x = customData.x;
custom.y = customData.y;
return custom;
}
var custom = new Custom;
custom.x = "foo";
custom.y = "bar";
localStorage.custom = custom;
console.log(Custom.unserialize(localStorage.custom).addChild());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With