I use such code to pass arguments to event handler functions. But, in this particular case the loop is causing problems. Only the last linkTags[i] is accesible in all activeVisual calls. This has to do with the fact that the anonymous function that passes the argument is one and the same for the entire loop.
for (var i = 0; i < linkTags.length; i++) {
addCrossEvent(linkTags[i], "click", launchLink);
addCrossEvent(linkTags[i], "mousedown",
function(evt) {
activeVisual(evt, linkTags[i]);
});
}
Now, I remember trying to add new before the anonymous function declaration like this:
for (var i = 0; i < linkTags.length; i++) {
addCrossEvent(linkTags[i], "click", launchLink);
addCrossEvent(linkTags[i], "mousedown",
new function(evt) {
activeVisual(evt, linkTags[i]);
});
}
It did not work. The activeVisual never gets called. Can somebody explain to me why and how can I make it work, please?
UPDATE FINAL SOLUTION
Thanks to all responses below my WORKING code now looks like this:
// Function that provides pass of event handling parameters with separate copy in each loop
function callbackHandler(index) {
return function(evt) {
activeVisual(evt, linkTags[index]);
}
}
...
for (var i = 0; i < linkTags.length; i++) {
...
addCrossEvent(linkTags[i], "mousedown", callbackHandler(i));
}