views:

352

answers:

3

is it possible to determining what object calls a function based on an event listener? for example, i have 2 buttons on stage that call the same function when they are clicked. i'd like the function to determine which button was the sender.

firstButton.addEventListener(MouseEvent.CLICK, myFunction);
secondButton.addEventListener(MouseEvent.CLICK, myFunction);

function myFunction(e:MouseEvent):void
 {
 var myString:String = "The button that called this function was (??)";
 trace(myString);
 }
+2  A: 

Use the property currentTarget from the Event class

function myFunction(e:MouseEvent):void {
 var myString:String = "The button that called this function was "+e.currentTarget;
 trace(myString);
}
Patrick
when you want the original sender `target` is better, if the event is bubbling currentTarget will be whatever the event is at when you catch it.
grapefrukt
+1  A: 

inside myfunction, e.currentTarget should hold a reference to the button that sent the event.

SP
+1  A: 

i just want to add to that: in the event object you get in the function there are two properties that sometimes can get confusing to differentiate between them :

e.target - the target will always return to you the original dispatcher of the event so if you clicked on a button but where listening to the parent your target would still be the button.

e.currentTarget - currentTarget returns the object you asked from the event or in adobes language "The object that is actively processing the Event object with an event listener. ".

so your currentTarget and target can produce different results and you need to keep that in mind. p.s. if your events don't bubble(non-visual /non user interaction mouse events) then your currentTarget and target would be the same or if you ask the object that dispatched the event in the case of a bubbling event.

-- EventController - AS3 Event management made easy.

http://fla.as/ec/

Ben Fhala