PDA

View Full Version : callback button function in a "for" loop



fRedline
March 29th, 2005, 03:49 PM
The type of "for loop" in question:

for (i=1; i<5; i++) {
theClip="clip"+i;
eval(theClip).onPress = function() {
found(i); // passes the i variable to a hypothetical "found" function
}
}

"theClip" evaluates correctly, i.e. clip1, clip2, clip3, clip4.

The i inside the callback function is useless though. Every clip's onPress function will pass 4 (the last loop #) to the "found" function.

I must be totally missing some basic restriction on callbacks. Any help for a quick learner? Thank you!

stwingy
March 29th, 2005, 03:59 PM
The type of "for loop" in question:

for (i=1; i<5; i++) {
theClip="clip"+i;
eval(theClip).onPress = function() {
found(i); // passes the i variable to a hypothetical "found" function
}
}

"theClip" evaluates correctly, i.e. clip1, clip2, clip3, clip4.

The i inside the callback function is useless though. Every clip's onPress function will pass 4 (the last loop #) to the "found" function.

I must be totally missing some basic restriction on callbacks. Any help for a quick learner? Thank you!

for (i=1; i<5; i++) {
this["clip"+i].ivar = i;
this["clip"+i].onPress = function() {
found(this.ivar);
// passes the i variable to a hypothetical "found" function
};
}

fRedline
March 29th, 2005, 09:18 PM
stwingy code
Ah, quite elegant, and insightful. I thank you so much for taking the time to illustrate a powerful leverage of method reference.

I've applied the same to some nested functions and it's a real beauty.