I have asked and have been asked by fellow designers who are learning ActionScript, “How do I pass a variable to a function when using the addEventListener to call a function in ActionScript 3?” Passing a variable to a function in ActionScript 2 was a fairly simple task. However, it is not so easy using addEventListeners in ActionScript 3. There are a few more things you must do first.
The purpose of this is to help designers or those who are new to ActionScript 3 understand how to pass a variable to a function when using the addEventListener to call a function.
/* set up the "b" Array using the instance names of the
buttons located on the stage */
var b:Array = [b1_btn, b2_btn, b3_btn];
/* set up the "a" Array using the correct string values. These
can be links, text, ect... */
var a:Array = ["zero","one","two"];
/* set up the For Loop which will iterate through the "b" Array
*/
for (var i:int = 0; i<b.length; i++) {
b[i].addEventListener(MouseEvent.CLICK,
clickedOne);
function clickedOne(e:MouseEvent):void {
/* set up the For Loop which will
iterate through the "a" Array */
for (var j:int = 0; j<a.length; j++) {
if (e.currentTarget.name == b[j].name)
{
doThis(a[j])
}
}
}
}
/* This function will be called for the button clicked. */
function doThis(v:String):void {
/*Place whatever code you need in
here*/
trace(v);
}
Download the soruce file here.
If you have questions, feel free to drop me a line.
Thanks to
Mykola Bilokonsky
for the comment below showing another
solution to the same problem.
Good luck with your project.
+