刷新HTML 5 Localstorage后恢复应用程序数据数组

时间:2013-06-23 16:49:43

标签: jquery html5 local-storage

我有一个数组,我的应用程序依赖于渲染数字和div。我希望通过HTML 5 localStorage API在本地存储它。这是我的JS代码

var app = {
slidePreviews: "",
slideDuration: 7000,
presentation: {
    title: "",
    theme: "themeName",
    slides: []
},
themes: [{
    name: "white",
    css: "whitetheme",
    slideControls: ""
}, {
    name: "black",
    css: "blacktheme",
    slideControls: ""
}, {
    name: "red",
    css: "redtheme",
    slideControls: ""
}, {
    name: "blue",
    css: "bluetheme",
    slideControls: ""
}, {
    name: "orange",
    css: "orangetheme",
    slideControls: ""
}, {
    name: "green",
    css: "greentheme",
    slideControls: ""
}]
};

$(document).ready(function () {

var saved = false;

var handlers = {

    savePresentationData: function(event){

        // Place the app object into storage
        localStorage.setItem("app", JSON.stringify(app));

        // Retrieves the object app from HTML 5 local storage
        var retrievedObject = localStorage.getItem("app");

        console.log("retrievedObject: ", JSON.parse(retrievedObject));

        var savedData = JSON.parse(retrievedObject);

        var saved = true;
        return savedData;
    },

    clearAppData: function(event){
        localStorage.clear();
        return false;
    }

};

//use localstorage to restore presentaton data
if(saved){
    app = JSON.parse(retrievedObject);
}

我不确定我是否正确行事。它不是在刷新时工作。刷新后,app对象不包含我之前保存的数据。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我认为你错了。您不能期望在页面刷新后存在saved变量吗?您必须检查来自localStorage的数据是否为null,并将您的代码作为基础:

window.onload = function () {
    //get data from localStorage
    var saved = handlers.getPresentationData();
    //check if its null / undefined
    if ([null, undefined].indexOf(saved) === -1) {
        //its not null/undefined - data exists!
        console.log("Data exists. Here's the data : ", saved);
        //set your "app" to data from localStorage
        app = saved;

        //Do whatever you want with app - Im choosing to ask for deleting
        if (confirm("Clear locally Stored data?")) {
            handlers.clearAppData();
        }

    } else {
        //data DOES NOT exist in localStorage
        console.log("Data does not exist, save to localStorage");
        //So, save it in localStorage. Refresh this page now.
        handlers.savePresentationData();
    }

};

哦,你需要三个处理程序,

  • 保存
  • 获取
  • 清除
像这样:

var handlers = {
    savePresentationData: function () {
        // Place the app object into storage
        localStorage.setItem("app", JSON.stringify(app));
    },
    getPresentationData: function () {
        // Retrieves the object app from HTML 5 local storage
        var retrievedObject = localStorage.getItem("app");
        var savedData = JSON.parse(retrievedObject);
        return savedData;
    },
    clearAppData: function (event) {
        localStorage.clear();
        return false;
    }
};

演示:http://jsbin.com/icafac/1/edit

我已删除的内容:

  • event参数传递给处理程序中的函数。
  • 用于saved / true
  • false变量现在用于保存localStorage
  • 中的数据

希望这有帮助!

答案 1 :(得分:0)

您需要一个处理程序来加载您的数据,还需要一个来保存它。尝试加载数据,并传递默认值。如果加载失败,该函数将返回您设置的默认值:

var app = { .. values .. },
handlers = {
    loadPresentatioData: function (defaults) {
        /**
         * Retrieve stored value
         */
        var loaded = localStorage.getItem('app');

        /**
         * Use defaults if no stogare is found
         */
        if (!loaded) {
            localStorage.setItem('app',JSON.stringify(defaults));
            loaded = localStorage.getItem('app');
        }

        /**
         * Prevent errors if the parsing goes wrong
         * Defaults to original app value
         */
        try {
            loaded = JSON.parse(loaded);
        }
        catch (e) {
            loaded = defaults;
        }

        return loaded;
    },
    savePresentationData: function (data) {
        var serialized;

        try {
            serialized = JSON.stringify(data);
            localStorage.setItem('app',serialized);
        }
        catch (e) {
            // Something went wrong
        }
    }
};