开发者

How to save an object to a database as json string and reload later?

开发者 https://www.devze.com 2023-04-01 12:28 出处:网络
So I have a Module object, and I have a AdvModule object which inherits from Module using the following:

So I have a Module object, and I have a AdvModule object which inherits from Module using the following:

function object(o) {
    function F() { }
    F.prototype = o;
    return new F();
}
function inheritPrototype(subtype, supertype) {
    var prototype = object(supertype.prototype);
    prototype.constructor = subtype;
    subtype.prototype = prototype;
}

inheritPrototype(AdvModule, Module);

Module has a object variable called 'settings' which contains things such as X, Y, height, width, etc. Currently I am saving those settings to a database in json format. Then when the page is refreshed those settings are pulled from the database to recreate that Module.

But now I have AdvModule as well, and there isn't anything currently in the settings that indicate what kind of object it is supposed to be. I know that I can just assign a string value and use that in a switch statement to decide what objects get built using those settings, but I would like to avoid the switch statement as the number of objects inheriting from Module is volatile and I don't want other developers to have to go in and continuously change the switch statement. I want the settings to know what object is to be built.

I have tried adding another value to 'settings' that is开发者_运维百科 the name of the object: i.e -> {type:AdvModule} and I use this when loading like so-> item = new settings.type(); Which seems to work. But when I go to save this to my database JSON.Stringify seems to throw it out or ignore it.

Any help/advice would be greatly appreciated. Thanks


{ type : AdvModule } is not valid JSON object unless AdvModule is a string, number, array, or JSON object (not a JavaScript object, rather an object as defined by JSON, i.e. "an unordered set of name/value pairs"[1]). If AdvModule is a class or other complex JavaScript object then JSON.stringify will indeed just throw it out.

The solution is to store the name of the object instead of the object itself, i.e.:

var settings = { type : "AdvModule" };

Then when you want to instantiate it you'll do something like this:

var thing = new window[settings.type];

This is equivalent to calling new window.AdvModule (if AdvModule isn't in the global namespace, i.e. window, replace window with the correct context).

0

精彩评论

暂无评论...
验证码 换一张
取 消