0

I have 1 to 64 buttons called(instance name) b1 - b64. I need to add mouse click event to every buttons.My current code like this....

b1.addEventListener(MouseEvent.CLICK, btn1click);
function btn1click(event:MouseEvent)
{
 var e = b1;
}
b2.addEventListener(MouseEvent.CLICK, btn2click);
function btn2click(event:MouseEvent)
{
 var e = b2;
}
b3.addEventListener(MouseEvent.CLICK, btn3click);
function btn3click(event:MouseEvent)
{
 var e = b3;
}
.......

I need to reduce that repetition.

2

1 Answer 1

1

You can use a loop to attach the event listeners to the buttons:

for (var i:int = 1; i <= 64; i++) {
    this['b' + i].addEventListener(MouseEvent.CLICK, btnClick);
}

And use a single listener function:

function btnClick(event:MouseEvent):void {
    trace(event.currentTarget + ' was clicked.');
}
Sign up to request clarification or add additional context in comments.

2 Comments

trace(event.currentTarget.name + ' was clicked.'); //Edit
@VirajTharinda You know it.

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.