Question

I'm trying to create a setup object with all app URL's in it but some of the URL values are dynamic and stored in the local storage. My question is how do I update a setup object based on latest local storage?

HTML:

<a href="javascript:slideonlyone('addon1')">Addon 1</a>
<a href="javascript:slideonlyone('addon2')">Addon 2</a>
<a href="javascript:slideonlyone('addon3')">Addon 3</a>

Javascript:

window.localStorage.setItem('TmpAdd','default');

var AppUrl = {
    'jsonUrl1' : 'http://myurl.com/' + window.localStorage.getItem('TmpAdd'),
    'jsonUrl2' : 'http://myurl.com/category/' + window.localStorage.getItem('TmpAdd')
};

function slideonlyone(item) {
    window.localStorage.setItem('TmpAdd', item );
    console.log(window.localStorage.getItem('TmpAdd'),AppUrl.jsonUrl1);      
}

See working example here:

http://codepen.io/anon/pen/BebvE/

Était-ce utile?

La solution

Update the URLs whenever you change the local storage values:

var AppUrl = { };
updateURLs('default');

function updateURLs(tmpAdd) {
    window.localStorage.setItem('TmpAdd', tmpAdd);
    AppUrl.jsonUrl1 = 'http://myurl.com/' + tmpAdd;
    AppUrl.jsonUrl1 = 'http://myurl.com/category/' + tmpAdd;
}

function slideonlyone(item) {
    updateURLs(item);
    console.log(window.localStorage.getItem('TmpAdd'));
    console.log(AppUrl.jsonUrl1);
}

Another way would be to turn jsonUrl1 and jsonUrl2 into functions that look at the current value of localStorage.TmpAdd and create a URL appropriately. You could make the functions look like ordinary properties by using custom property gettersMDN, but this is probably an overkill.

var AppUrl = {

    'jsonUrl1' : function() {
        return 'http://myurl.com/' +
            window.localStorage.getItem('TmpAdd');
    },

    'jsonUrl2' : function() {
        return 'http://myurl.com/category/' +
            window.localStorage.getItem('TmpAdd');
    }
};

// usage: replace AppUrl.jsonUrl1 with AppUrl.jsonUrl1()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top