0

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.

}

2 Answers 2

3

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.
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.