Reputation: 1
I am trying to create a system that displays the name of the button that you press. The button names are put into an array, however it only recognized the last item entered into the array. Help would be greatly appreciated.
var items:Array = [a, b, c]; //The name of each button
for each(var index in items)
{
index.addEventListener(MouseEvent.CLICK, mouseClickHandler);
}
function mouseClickHandler(event:MouseEvent):void
{
trace(index.name); //Should display the name of any of the buttons clicked.
}
Upvotes: 0
Views: 349
Reputation: 416
You should trace the currentTarget
name:
var items:Array = [a, b, c]; //The name of each button
for each(var index in items) {
index.addEventListener(MouseEvent.CLICK, mouseClickHandler);
}
function mouseClickHandler(event:MouseEvent):void {
trace(event.currentTarget.name); //Should display the name of any of the buttons clicked.
}
Upvotes: 3
Reputation: 106483
There's only one index
variable created here - and mouseClickHandler
function, obviously, works with its current value only. If you need to refer to specific values (given at each loop step), you need to localize them in one way or another:
function generateClickHandler(index:someType) {
return function(event:MouseEvent):void { trace(index.name); }
}
...
for each(var index in items)
{
index.addEventListener(MouseEvent.CLICK, generateClickHandler(index);
}
I'd suggest checking this thread as well.
Upvotes: 0