views:

68

answers:

2

Hi, I am stumped by a problem which i'd assume is a common Jquery occurence, but i've no idea how to fix!

I have 5 variables -

 var pubtimed 
 var toolstimed 
 var newstimed 
 var mylinkstimed 
 var partnerstimed 

Which are used to store on and off states.
I then have a script that checks cookies for recent states and updates the variables accordingly, then forwards the details onto a render function -

var map = {
    'pub': $.cookie('nwphportal_tabExpPub'),
    'tools': $.cookie('nwphportal_tabExpTools'),
    'news': $.cookie('nwphportal_tabExpNews'),
    'mylinks': $.cookie('nwphportal_tabExpLinks'),
    'partners': $.cookie('nwphportal_tabExpPartners')
}

$.each(map, function (key, value) {
    if (value != null) {
        var varname = key + 'timed';
        varname = value;
        renderScrn(varname)
    } else {
        var varname = key + 'timed';
        varname = "1"
        renderScrn(varname)
    }
});

The problem I have is that I want the variable varname to be treated as each of the 5 variables above (e.g. key plus timed = pubtimed). But this doesnt happen and I just get an error. I could just place a list of if statements to fix this, but wondered if there were a better solution?

Please help if you can!

Cheers for your time. Paul

+2  A: 
Pointy
Spot on, works a treat - thanks very much for your help!
Paul
+1 for correct answer to immediate problem. But it is also worth considering a cleaner approach.
Pekka
Yes I agree, @Pekka; I wouldn't code it like that. Such is life on StackOverflow :-) (I'll add to my answer.)
Pointy
+3  A: 

I would go for namespacing, encapsulating the related data into one object:

var timed = {};

$.each(map, function (key, value) {

    if (value != null) {
        timed[key] = value;
        renderScrn(varname);
    }

    else {
        timed[key] = 1;
        renderScrn(varname);
    }
});​

So you can call them timed.partners, timed.pub, and so on...

galambalazs
+1 for clean approach
Pekka
cool cheers, both solutions work great. thanks for your time
Paul
it's always the best too keep your global namespace clean and sparate your code.
galambalazs