How to convert a string to variable name

Posted by p1xelarchitect on Stack Overflow See other posts from Stack Overflow or by p1xelarchitect
Published on 2014-06-06T09:20:15Z Indexed on 2014/06/06 9:25 UTC
Read the original article Hit count: 130

Filed under:
|
|

I'm loading several external JSON files and want to check if they have been successfully cached before the the next screen is displayed. My strategy is to check the name of the array to see if it an object. My code works perfectly when I check only a single array and hard code the array name into my function. My question is: how can i make this dynamic?

not dynamic: (this works)

$("document").ready(){
    checkJSON("nav_items"); 
}

function checkJSON(){

   if(typeof nav_items == "object"){
       // success...
   }

}

dynamic: (this doesn't work)

$("document").ready(){
    checkJSON("nav_items"); 
    checkJSON("foo_items"); 
    checkJSON("bar_items"); 
}

function checkJSON(item){

   if(typeof item == "object"){
       // success...
   }

}

here is the a larger context of my code:

var loadAttempts = 0;  
var reloadTimer = false;  



$("document").ready(){
    checkJSON("nav_items"); 
}



function checkJSON(item){

loadAttempts++;

//if nav_items exists
if(typeof nav_items == "object"){

        //if a timer is running, kill it
        if(reloadTimer != false){
        clearInterval(reloadTimer);
        reloadTimer = false;
    } 
    console.log("found!!");
    console.log(nav_items[1]);
    loadAttempts = 0; //reset

            // load next screen....                   

} 

//if nav_items does not yet exist, try 5 times, then give up!
else {
            //set a timer
    if(reloadTimer == false){
        reloadTimer = setInterval(function(){checkJSON(nav_items)},300);
        console.log(item + " not found. Attempts: " + loadAttempts );
    }
            else {
        if(loadAttempts <= 5){
            console.log(item + " not found. Attempts: " + loadAttempts          );
        } else {
            clearInterval(reloadTimer);
            reloadTimer = false;
            console.log("Giving up on " + item + "!!");
        }
    }
}

}

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery