I'm trying to generate dynamic functions to use as separate
callbacks for an AJAX API call.
The API doesn't seem to allow for the inclusion of any parameters
in the callback, so I can't associate the call with the handling
routine (for reference purposes, I'm calling the Google Language
Translation API). As a work-around, I thought I'd dynamically
generate a unique callback function for each API call.
Right now, I'm stuck hobbling the API calls by running them
synchronously, since they don't seem to allow parameterizing the
callback function. This rather slows things down.
Of course, since I haven't gotten my work around running, I can't
prove that it will have the desired effect of parellizing the API
calls for me.
I'm running into what are probably some fairly basic issues when
generating the function definitions (and probably the initial calling
API code, but since I haven't gotten that far, I'm not sure yet).
For example:
for (i = 0; i < 10; i++) {
var text = 'Test [' + eval( i ) + ']';
window[ 'alerter' + i ] = function () { alert ( text ); }
}
This code generates my ten functions (alerter0(), alerter1(),
alerter2(), etc) but the body of the functions seems to be getting the
variable reference to 'i', instead of the string literal value of 'i'
during that loop iteration. So when I execute any of the 'alerterX()'
functions, they /all/ pop up alert boxes using the referenced value of
'i' at the end of the loop, instead of the intended effect where
'alerter0()' would have the text 'Test [0]', 'alerter1()' would have
the text 'Test [1]', etc.
The goal is to build an arbitrary number of unique callback
functions of the model:
// myelements[] is a global array of html elements where the text is
being replaced with the returned value
function callBackXX(resu lt) {
if (result.transla tion) {
myelements[XX].innerHTML = result.translat ion;
} else {
myelements[XX].innerHTML = '';
}
}
With calls along the model of:
google.language .translate(text , 'en', 'es', callBack0 );
google.language .translate(text , 'en', 'es', callBack1 );
google.language .translate(text , 'en', 'es', callBack2 );
With these calls, obviously, being dynamically generated in the
loop as well.
Any pointers on how to generate the required static strings for
the function bodies, instead of getting variable references would be
appreciated. I'd like to avoid using eval() (Yes, I know my example
used it!), as well.
Thanks in advance.
-Joe
Comment