0

I have an array that my application depends on for rendering figures and divs. I wish to store this locally through HTML 5 localStorage API. Here's my JS code

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);
}

I am not sure if I am doing this right. It is not working upon refresh. Upon refresh, the app object does not contain the data I saved before.

ANy suggestions?

1
  • Could you give an example of the scenario? Where are you getting the data from? Is it like that? Static in your js file or do you retrieve them from the server (ajax)? Commented Jun 23, 2013 at 17:33

2 Answers 2

1

I think you're going by this wrong. You cant expect saved variable to exist after page refresh can you? You have to check if the data from localStorage is null or not and base your code on that :

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();
    }

};

Oh, and you need three handlers,

  • Save
  • Get
  • Clear

like this :

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;
    }
};

Demo : http://jsbin.com/icafac/1/edit

Things I've removed :

  • Passing event argument to function in handlers.
  • saved variable which was used for true/false is now used for saving data from localStorage

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

You need one handler to load your data, and one to save it. Try loading the data, and pass a default value. If the load fails, the function will return the defaults you've set:

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
        }
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.