最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Saving Javascript Module Object in local storage - Stack Overflow

programmeradmin1浏览0评论

i have a javascript module name SceneModule, see the code snippet below

var SceneModule = function()    {
    var scene, createScene, updateScene, getScene;

    scene   =   {
        name : '',
        width : 100,
        height : 100
    };

    createScene = function(params)  {
        for(var key in params)  {
            scene[key] = params[key];
        }

        return this;
    };

    updateScene = function(params)  {
        scene[params.attr] = params.value;
    };

    getScene = function()   {
        return scene;
    }

    return {
        create : function(params)   {
            createScene(params);
        },

        update : function(params)   {
            updateScene(params);
        },

        get : function()    {
            getScene();
        }
    };
};

var SceneArray = [], tempArray;

SceneArray.push(
    SceneModule.create({
        name : 'scene 1',
        width : 100,
        height : 100
    }),
    SceneModule.create({
        name : 'scene 2',
        width : 100,
        height : 100
    }),
    SceneModule.create({
        name : 'scene 3',
        width : 100,
        height : 100
    })
);

localStorage.setItem('scene',JSON.stringify(SceneArray);

tempArray = JSON.parse(localStorage.getItem('scene'));

/**
 * Print string [object object, object object, object object];
 * not the SceneArray Structure; 
 */
console.log(tempArray);

When I put the array of object to local storage and retrieve it, I get a string ([object object, object object, object object]) not the object array itself. I am also new to the modular architecture and local storage. I tried what many levels that i know to store and get the array of object. please review the code block. thanks in advance

i have a javascript module name SceneModule, see the code snippet below

var SceneModule = function()    {
    var scene, createScene, updateScene, getScene;

    scene   =   {
        name : '',
        width : 100,
        height : 100
    };

    createScene = function(params)  {
        for(var key in params)  {
            scene[key] = params[key];
        }

        return this;
    };

    updateScene = function(params)  {
        scene[params.attr] = params.value;
    };

    getScene = function()   {
        return scene;
    }

    return {
        create : function(params)   {
            createScene(params);
        },

        update : function(params)   {
            updateScene(params);
        },

        get : function()    {
            getScene();
        }
    };
};

var SceneArray = [], tempArray;

SceneArray.push(
    SceneModule.create({
        name : 'scene 1',
        width : 100,
        height : 100
    }),
    SceneModule.create({
        name : 'scene 2',
        width : 100,
        height : 100
    }),
    SceneModule.create({
        name : 'scene 3',
        width : 100,
        height : 100
    })
);

localStorage.setItem('scene',JSON.stringify(SceneArray);

tempArray = JSON.parse(localStorage.getItem('scene'));

/**
 * Print string [object object, object object, object object];
 * not the SceneArray Structure; 
 */
console.log(tempArray);

When I put the array of object to local storage and retrieve it, I get a string ([object object, object object, object object]) not the object array itself. I am also new to the modular architecture and local storage. I tried what many levels that i know to store and get the array of object. please review the code block. thanks in advance

Share Improve this question edited Jan 27, 2012 at 6:44 Grace Huang 5,7195 gold badges34 silver badges55 bronze badges asked Jan 27, 2012 at 6:28 Jaison JustusJaison Justus 2,7938 gold badges48 silver badges66 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

No. You cannot store functions or closures in localStorage. This means that you cannot store state stored in closures explicitly in localStorage.

Your current code actually prints [null, null, null] because it's broken.

After fixing your code it correctly prings [{}, {}, {}] because you only have methods

Mainly because JSON doesn't support functions. There are two solutions

Use a real prototypical OO module

Live Example - Here I'm using pd-style prototypical OO

var Scene = { 
    /* insert methods */   
};

var SceneArray = [], tempArray;

SceneArray.push(
    extend(Object.create(Scene), {
        name : 'scene 1',
        width : 100,
        height : 100
    }),
    extend(Object.create(Scene), {
        name : 'scene 2',
        width : 100,
        height : 100
    }),
    extend(Object.create(Scene), {
        name : 'scene 3',
        width : 100,
        height : 100
    })
);

localStorage.setItem('scene', JSON.stringify(SceneArray));

tempArray = JSON.parse(localStorage.getItem('scene')).map(function (data) {
    return extend(Object.create(Scene), data);
});
console.log(tempArray); // [Object, Object, Object]

Here only methods go on the Scene prototype and you extend your object that inherits from Scene with the actual data. You store the actual data in localStorage and when you take it out of local storage you map them to objects that inherit from Scene to get your methods back.

Implement a save and load function

Live Example - The trick here is to save the data and then pack the data into a SceneModule object.

// unpack the data and only save the data
localStorage.setItem('scene', JSON.stringify(SceneArray.map(function (scene) {
    return scene.get();
})));

// pack the data back into a scene module.
var tempArray = JSON.parse(localStorage.getItem('scene')).map(function (data) {
    return SceneModule().create(data);
});

Note that unlike the prototypical OO example you have to unpack your objects in the save stage. Prototypical OO has the advantage of your objects just being your state and because only the properties own data are it's own properties it's pletely safe to just save the object without modification.

发布评论

评论列表(0)

  1. 暂无评论