views:

18

answers:

1

I am trying to utilize Google's AJAX Language API to translate each value in an array.

for(var n=0; n < mytext.length; n++) {
 google.language.translate(mytext[n], originalLanguage, newLanguage, function(result){
  if(!result.error){
   document.getElementById("caption") += mytext[n]+" has been translated to "+result.translation;
  }
 })
}

This correctly translates the entire array, but in the success function called by google.language.translate, n is always equal mycaptions.length. This results in mycaptions[n] returning as undefined (e.g., " has been translated to Hola"). This has been bewildering me for days (why is the value of n inside the callback function always as if you are at the end of the loop???), and I am guessing the answer lies in an obvious bit of programming I just don't get.

+1  A: 

This has to do with how closures work in JavaScript; when JavaScript creates a closure, any variables that get used are referenced, rather than copied, so when you construct the anonymous function, it stores a reference to n rather than copying the value of n. Hence, when it actually gets called, it runs with the current value of n (which is the value that gets assigned to it at the end of the loop). The workaround is to create a function that takes a parameter n and returns a closure:

function createSuccessFunction(n) {
    return function() {
          // behavior on success
    };
}

// use createSuccessFunction(n) where you need a callback
Michael Aaron Safyan