I am using the Microsoft Translation api (AJAX Version) from http://www.microsofttranslator.com/dev/
I am having some issues with closures and callbacks, which I hope this code will demonstrate:
function translate(original){
window.translateComplete = function(language) {
if (language!="en"){
alert(original +" "+language);
}
}
var windowsliveid = 'API_KEY_REMOVED';
var el = document.createElement("script");
el.src = 'http://api.microsofttranslator.com/V2/Ajax.svc/Detect';
el.src += '?oncomplete=translateComplete';
el.src += '&appId=' + windowsliveid;
el.src += '&text=' + escape (original);
document.getElementsByTagName('head')[0].appendChild (el);
}
translate("Au Revoir");
translate("Hola");
Now, my response comes back as
Hola es
Hola fr
The original variable is being overwritten, before the callback has had a chance to execute.
How do I avoid this so that it displays something like:
Hola es
Au revoir fr
I am trying to do this without using jQuery and when()
Thanks
Well, you are using the same callback function for every response, since
window. translateCompletecan only refer to one function. So every call totranslatewill overwritewindow.translateCompletewith a new function, which is a closure.You could create a new callback with a different name for each call. That’s what jQuery is doing.
In it’s simplest form: