I'm new to programming and apologize up front if I misuse terminology.
In a 'for loop' I'd like to add an event listener to a series of buttons. For each button I'd like to define a different function. Is it possible to pass the variable through when the functions are being named?
My buttons all have sequentially named instance names.
Here's my code:
for (var cBut:int = 1; cBut < 4; c开发者_StackOverflowBut++)
{
this["c" + cBut].addEventListener(MouseEvent.CLICK, ["orangeValue" + cBut]);
}
And the resulting error: TypeError: Error #1034: Type Coercion failed: cannot convert []@42f50a89 to Function.
Thanks in advance for any help.
That is saying "Add an event listener to this["c" + cBut]
. Listen for MouseEvent.CLICK, and when that happens fire the function new Array( "orangeValue" + cBut )
. Arrays can't handle functions, and the only element in that array will be a String.
What you want is this["orangeValue" + cBut].<whatever function handles click>
. (Functions are what are needed to listen to events in AS3. That's different from AS2). Your best bet is actually to use a helper function too -- it guarantees no scoping issues:
for (var cBut:int = 1; cBut < 4; cBut++)
{
helper( cBut );
}
function helper( cBut:int ):void
this["c" + cBut].addEventListener(MouseEvent.CLICK,
this["orangeValue" + cBut].clickHandler);
}
精彩评论