1

I want to make multiple button function with this function

for(var i=1; i <= 3; i++){this["btn"+i].addEventListener(MouseEvent.CLICK, someFunction);}

then, every i clicked some button, i want it to trace some number that exactly same with [i]. Lets say i clicked 'btn1' then it trace '1'. What should i do? Thankyou. Beginner at flash.

1 Answer 1

1

The key is knowing that event object, that is passed to subscribed methods also carries a reference to the source of the event.

function someFunction(e:Event):void
{
    // Get the reference to the button and access its name.
    var aButton:DisplayObject = e.currentTarget as DisplayObject;
    var aName:String = aButton.name;

    // If all the buttons are named in the way you put it:
    // Extract digits.
    var aDigits:String = aName.substr(3);

    // Convert them into number.
    var anIndex:int = int(aDigits);

    // Profit!
    trace(anIndex);
}

UPD. As Vesper pointed out below, it needs some explanation.

There are two references in the event object: e.target and e.currentTarget, that might or might not be the same:

  • e.target is the original source of event
  • e.currentTarget is the object you subscribed the event handler to

Let us think how MouseEvent.CLICK occurs. You click a button. At the same time you click a MovieClip/Sprite that contains the button. All their parents. Finally, Stage. So the e:MouseEvent starts at the button so the button dispatches it, then it bubbles (this process is called bubbling, read this: Event Bubbling, and Stop Propagation) one level up, then button parent fires the event, and so on all the way up to stage.

There are also 2 properties that can change the result of event handling:

Sign up to request clarification or add additional context in comments.

3 Comments

Mention e.target also. In this particular situation target==currentTarget, but it's not always the case.
@Vesper In this particular situation e.target exactly might not be equal e.currentTarget, because for mouse events e.target is the deepest chilld (that is able to interact with mouse) of e.currentTarget
Hmm true, this really depends on what are those buttons. Okay :)

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.