Skip to content Skip to sidebar Skip to footer

How To Pass Additional Arguments To Callback Functions In Javascript When Using .execute()?

I'm working with javascript for Google Analytics API but I'm no more than a novice in JS. I have C++ and Java knowledge and I can get along with logical thinking but some things pu

Solution 1:

Adding a closure would solve your problem:

for(var x = 0; x< n x ++){  //Or any other loop
   (function(x){   //Closure. This line does the magic!!var arrayDim = something_that_depends_on_x_or_the_loop,
           param2 = some_other_thing_that_depends_on_x;
       gapi.client.analytics.data.ga.get({'ids':'<tableID>',
         'start-date':'<startDate>',
          ...
       }).execute(functionputToVar(results){   //this fn is defined inline to get access to param1, param2//The following alerts will use the *correct* variables thanks to the closurealert(x);
           alert(arrayDim);
           alert(param2);
       });
   })(x); //This one too
}

The closure does the magic. It will allow to each loop cycle to have its own variables (not shared), so the proper ones will be inside putToVar when executed.

I hope it's clear, if not, just let me know.

Just test it!

Cheers, from La Paz, Bolivia

Post a Comment for "How To Pass Additional Arguments To Callback Functions In Javascript When Using .execute()?"