PDA

View Full Version : passing arguments to event handlers in loop?



dragonfly
May 8th, 2009, 04:14 PM
I'm having some AS3 growing pains....

Say I have an array with 4 string elements that are 4 different urls. On the stage I have 4 movieclips that I want to have listen for a CLICK event. When the user clicks a button, the navigate to one of the 4 urls.

I can loop through the buttons and add and event listener to each:

private function applyPlankLinks():void {
for (var i:uint = 0; i<numberOfPlankBtns; i++) {
maskedStuff_mc["plankbtn"+i].addEventListener(MouseEvent.CLICK, navToURL);
}
}But how can I tell navToURL what each of the urls are for each of the buttons??

Am I approaching this all wrong?

here's what I'm doing now, which would not work if the number of buttons/links was unknown, not to mention its verbose and not very sexy:

private function applyPlankLinks():void {
maskedStuff_mc.plankbtn0.addEventListener(MouseEve nt.CLICK, navToURL1);
maskedStuff_mc.plankbtn1.addEventListener(MouseEve nt.CLICK, navToURL2);
maskedStuff_mc.plankbtn2.addEventListener(MouseEve nt.CLICK, navToURL3);
maskedStuff_mc.plankbtn3.addEventListener(MouseEve nt.CLICK, navToURL4);

}
private function navToURL1(event:Event):void {
var request:URLRequest = new URLRequest(plankBtnLinks[0]);
navigateToURL(request);
}
private function navToURL2(event:Event):void {
var request:URLRequest = new URLRequest(plankBtnLinks[1]);
navigateToURL(request);
}
private function navToURL3(event:Event):void {
var request:URLRequest = new URLRequest(plankBtnLinks[2]);
navigateToURL(request);
}
private function navToURL4(event:Event):void {
var request:URLRequest = new URLRequest(plankBtnLinks[3]);
navigateToURL(request);
}Please help!!!

senocular
May 8th, 2009, 04:32 PM
save the urls in the button and then in navToURL reference them using event.currentTarget.url (url or whatever you named the variable where the URLs are stored)

dragonfly
May 8th, 2009, 04:53 PM
Awesome. Thanks so much.