Difference between e.target and e.currentTarget - actionscript-3

I don't understand the difference, they both seem the same but I guess they are not.
Any examples of when to use one or the other would be appreciated.

e.target is what triggers the event dispatcher to trigger and e.currentTarget is what you assigned your listener to.

Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target, e.currentTarget work in relation to mouse events and the display list:
e.target = The thing under the mouse (as ben says... the thing that triggers the event).
e.currentTarget = The thing before the dot... (see below)
So if you have 10 buttons inside a clip with an instance name of "btns" and you do:
btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
trace(e.target.name, e.currentTarget.name);
}
e.target will be one of the 10 buttons and e.currentTarget will always be the "btns" clip.
It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren to false, e.target and e.currentTarget will both always be "btns".

I like visual answers.
When you click #btn, two event handlers get called and they output what you see in the picture.
Demo here: https://jsfiddle.net/ujhe1key/

e.currentTarget is always the element the event is actually bound do. e.target is the element the event originated from, so e.target could be a child of e.currentTarget, or e.target could be === e.currentTarget, depending on how your markup is structured.

target is the element that triggered the event (e.g., the user clicked on)
currenttarget is the element that the event listener is attached to.

It's worth noting that event.target can be useful, for example, for using a single listener to trigger different actions. Let's say you have the typical "menu" sprite with 10 buttons inside, so instead of doing:
menu.button1.addEventListener(MouseEvent.CLICK, doAction1);
menu.button2.addEventListener(MouseEvent.CLICK, doAction2);
etc...
You can simply do:
menu.addEventListener(MouseEvent.CLICK, doAction);
And trigger a different action within doAction(event) depending on the event.target (using it's name property, etc...)

make an example:
var body = document.body,
btn = document.getElementById( 'id' );
body.addEventListener( 'click', function( event ) {
console.log( event.currentTarget === body );
console.log( event.target === btn );
}, false );
when you click 'btn', and 'true' and 'true' will be appeared!

e.currentTarget would always return the component onto which the event listener is added.
On the other hand, e.target can be the component itself or any direct child or grand child or grand-grand-child and so on who received the event. In other words, e.target returns the component which is on top in the Display List hierarchy and must be in the child hierarchy or the component itself.
One use can be when you have several Image in Canvas and you want to drag Images inside the component but Canvas. You can add a listener on Canvas and in that listener you can write the following code to make sure that Canvas wouldn't get dragged.
function dragImageOnly(e:MouseEvent):void
{
if(e.target==e.currentTarget)
{
return;
}
else
{
Image(e.target).startDrag();
}
}

e.target is element, which you f.e. click
e.currentTarget is element with added event listener.
If you click on child element of button, its better to use currentTarget to detect buttons attributes, in CH its sometimes problem to use e.target.

e.currentTarget is element(parent) where event is registered, e.target is node(children) where event is pointing to.

Related

How to trigger mouse-click event on multiple HTML elements covering each other?

How to trigger multiple mouse-click events on arbitrarily many HTML elements covering each other?
I know you can use pointer-events: none; to let your click pass through your elements, but what if I want to trigger the mouse-click event on an element AND the mouse-click event on arbitrarily many other elements beneath it?
but what if I want to trigger the mouse-click event on an element AND the mouse-click event on arbitrarily many other elements beneath it?
Events bubble. Which means and event fired on an inner element, will also be received by the parent elements until the top most parent.
<div id="topmost">
<div id="second">
<p id="firstp"></p>
</div>
</div>
Assume you are using jquery. Below is how you would listen to click events from all elements below div.id="topmost".
Since the normal flow of events is for any click event (could be any other type of event) that is fired by any element with in the topmost div element will be bubbled to the outermost element, I only list to topmost click event and then check which element fired that event by checking the id of the target element. e.target will be the actual element that the click was performed on. You can either switch target.attr('id') or run it through if else conditions.
$(function () {
$("#topmost").on("click", function (e) {
e.preventDefault();
var target = $(e.target);
if(target.attr('id') === "idOfElement"){
// code to handle the event
}else{
});
A solution could be to track mouse move using :
$( document ).mousemove();
Store coordinates to a global variable then check its position when your element is clicked. That would give something like :
var mousePos = [0,0];
$( document ).mousemove(function( event ) {
mousePos[0] = event.pageX
mousePos[1] = event.pageY
});
$("#target").click(function(){
// Compare mouse coordinates and your items ones using offset, height and width
if(mousePos[0] > $('#target2').offset.left){
// Do whatever you are willing to do
}
});

AS3: What is the best way to put button-behaviors ONLY on child_mcs of a container_mc

I have a container_mc, with lots of child_mcs inside. I want the child_mcs to have full button-like behaviors (click-able, cursor effects).
I am not interested in putting individual mouse listeners on every child.
... I would like to simply have one listener on the parent container, though the parent would effectively be inactive ... only the child_mcs.
Delfine the common behaviour of the buttons in a class and associate that class with the button symbol in the library.
You could listen to click events on the container with the useCapture flag set to true (addEventListener's third argument) - the listener would be invoked every time any container's child (including grandchildren and so on) is clicked. Then you could check which button was clicked for example by examining its name property.
Let's assume you have something like this:
var container_mc:Sprite = new Sprite();
addChild(container_mc);
container_mc.addChild(button1);
container_mc.addChild(button2);
//and so forth with all your buttons
To do what you ask, you would do the following:
//add a click listener to the container
container_mc.addEventListener(MouseEvent.CLICK,click);
//make the buttonMode true on the container, so you get the button hand cursor
container_mc.buttonMode = true;
function click(e:Event):void {
//e.target is a reference to what was clicked (see caveat after code sample)
//if all the children of container_mc are of the same custom class,
//you could now call a click handler on that item
MyButtonClass(e.target).myClickHandler(e);
//or you could use a switch statement
switch(e.target){
case button1:
//button 1 was clicked, do something with it
break;
case button2:
//button 2 was clicked, do something with it
break;
}
}
The only caveat here, is an event's target could be any child down line of container. So if button1 had some children and those children had children, the object referenced in e.target could be any of them (which ever was clicked). If you have child object inside your button, then the easiest way to make sure your target is always the button, is do the following:
button1.mouseChildren = false;
That will ensure any mouse events dispatched by the button, will have button1 as the target and not any of it's children.
please ignore the downvote ... if your problem is the same as mine,
then this solution works
//-- pseudo code --\\
*for the container:*
container.addEventListener( MouseEvent.MOUSE_DOWN , callback_function ) ;
container.buttonMode ...... false
container.mouseEnabled .... false
container.mouseChildren ... true
*for each child:*
child.buttonMode ...... true
child.mouseEnabled .... true
child.mouseChildren ... false

AS3 MouseEvent and weakReference

Ok, here's a weird thing:
I have a class, which is a MovieClip that has 2 children, MovieClips also.
I add the children to him and base MovieClip to stage.One of the children is animated.
All is perfect.
Now when I add MouseEvent.MOUSE_UP on the children, all works fine.
Yet if I set useWeakReference to true (the 5th parameter) mouse event does not fire anymore,but the items are on stage. Basically, somehow, they are not in the memory.
Of course if I add a simple onEnterFrame that does nothing to base MovieClip, it traces the MovieClip, yet the MouseEvents does not trigger. That means the object is still there, but somehow for flash is not
Now, this is a simplified concept, that is easy to clean, but my code is very big and a simple removeEventListener is not a solution. At least not a simple one.
What are your suggestions to work around this?
I'm not sure how complex your code is, but if each movieclip has MOUSE_UP event handler - some function, you could indeed use removeEventListener MOUSE_UP function. For instance:
var mc:MovieClip = new MovieClip();
mc.addEventListener( MouseEvent.MOUSE_UP, onMU );
function onMU(e:MouseEvent){
var target = MovieClip(e.currentTarget);
target.removeEventListener( MouseEvent.MOUSE_UP, onMU );
}
This way you can have multiple movieclips and remove listeners without knowing object name.
Alternatively you could modify your code to add aray of all added events and then listen to REMOVE_FROM_STAGE event. Something like this:
var mc:MovieClip = new MovieClip();
mc.events = [];
mc.events.push( { evt: MouseEvent.MOUSE_UP, fn: onMU } );
mc.addEventListener( MouseEvent.MOUSE_UP, onMU } )
//or use events array reference to keep events and functions in one place.
//when object is removed you can iterate through events array and automatically remove
//all listeners
Another alternative would be to create Class that extends MovieClip - but since your code is huge you probably don't want to do that.
You can also look on Robert Penner's Signals library, which is interesting alternative to AS3 events. (https://github.com/robertpenner/as3-signals)

How can I recover an object who fires an eventListener event in AS3?

How can I access to an object who fires an eventListener event?
Let's say I have a mc:
var element = new MovieClip();
which has an eventlistener:
element.addEventListener(MouseEvent.CLICK, elementEventHandler);
And then, in the event handler, I want to add something to my mc:
function elementEventHandler(event:MouseEvent):void
{
var b1:balloon = new balloon("ballon1"); //this is another class.
event.target.addChild(b1);//this doesn't work.
}
So that is what I want to achieve... Recover the object who fired the event and then do crazy things with it (in this example, add another object in it).
If anybody has any idea, thanks in advance!
pd: yes, I know I can directly use the var element in this snippet, but in the real code I'm generating the mcs in a loop, according to a xml file.
function elementEventHandler(event:MouseEvent):void
{
// use the as-operator to cast the target into the class you need
var element:DisplayObjectContainer = e.target as DisplayObjectContainer;
// if the cast fails, element will be null, then we bail
if(!element) return;
// then, create your child and add it
var b1:balloon = new balloon("ballon1");
element.addChild(b1);
}
The reason you're getting an error is probably that the event is not coming directly from element but instead from one of its descendant objects.
"click" is a bubbling event.
Check out event flow in the DOM Level 3 Events spec to understand how the capture, target, and bubbling phases work:
http://www.w3.org/TR/DOM-Level-3-Events/#dom-event-architecture
So here's what I would do:
function elementEventHandler(event:MouseEvent):void
{
if (event.target != event.currentTarget)
// If event is not from "element", ignore it.
return;
...
}

I need help bubbling an event in AS3

I want to have the parent of my class handle the event first, then I want to have the child handle the event. Is there a way to explicitly bubble the event up? I want to do something like this:
...
this.addEventListener(MouseEvent.CLICK, characterClicked);
...
private function characterClicked(e:Event):void{
// pass event to parent to be handled first
...
}
Is this possible, and if so how?
There are three "phases" of an event; Capture, At target and Bubble. They occur in this order, meaning that if you set an event listener to be in the capture phase it will always fire before one set regularly (which would mean either at target or bubble).
Like so:
// in parent, third argument is "use capture"
child.addEventListener(MouseEvent.CLICK, handleClickInParent, true);
// in child, add listener as usual
addEventListener(MouseEvent.CLICK, handleClick);
Now, your parent event listener will always fire first!
I figured out a way to do this. Is seems hackish, but it works. If there is a better way of doing this please let me know.
...
this.addEventListener(MouseEvent.CLICK, characterClicked);
...
private function characterClicked(e:Event):void{
// pass event to parent to be handled first
this.removeEventListener(MouseEvent.CLICK, characterClicked); //prevent infinite loop
dispatchEvent(e); // send event to parent object
this.addEventListener(MouseEvent.CLICK, characterClicked);
e.stopImmediatePropagation();
...
}
If you were to handle the listener in the parent instead of the child it might be easier. Then you could just pass the event to the child when you're done:
// inside parent class:
childObj.addEventListener(MouseEvent.CLICK, onCharacterClicked);
private function onCharacterClicked(e:Event):void {
// do parent stuff first
// ...
// then pass event to child
childObj.onCharacterClicked(e);
}