Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom object classes in HTML5 LocalStorage?

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?

like image 330
Dylan Avatar asked Mar 04 '26 12:03

Dylan


1 Answers

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());
like image 158
Explosion Pills Avatar answered Mar 07 '26 02:03

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!