0
\$\begingroup\$

In the following code we use target in the function:

moon.mouseEnabled = false;
sky0.addChild(moon);

addEventListener(MouseEvent.MOUSE_DOWN, onDrag, false, 0, true);
addEventListener(MouseEvent.MOUSE_UP, onDrop, false, 0, true);

function onDrag(evt:MouseEvent):void {
    evt.target.addChild(moon);
    evt.target.startDrag();
}

function onDrop(evt:MouseEvent):void {
    stopDrag();
}

But if I rewrite this code without evt.target it still work. So what is the difference, am I going to get errors later in the run time because I didn't put target? If not then why some use target a lot while it works without it.

function onDrag(evt:MouseEvent):void {
    addChild(moon);
    startDrag();
}
\$\endgroup\$
1
  • \$\begingroup\$ "...am I going to get errors later in the run time..." You mean you didn't run it to see if it was the same? Just because two different methods both compile does not mean they are equivalent, just syntactically correct. \$\endgroup\$
    – House
    Commented Aug 26, 2012 at 16:43

1 Answer 1

1
\$\begingroup\$

The target property of an Event is the object that triggered the event! So if you mouse-down on a sprite on your stage, the "moon" object will get attached to the clicked sprite (because events bubble)!

So no, these examples don't do the same thing!

If you did this, then it would be the same thing:

evt.currentTarget.addChild(moon);

That is because currentTarget is always the object that had the event listener attached to. Generally, you should learn about scope. If your event handler function is on another object than the event listener was attached to, the two methods wouldn't do the same thing either.

Examples:

// this adds "moon" to the object that triggered the event
evt.target.addChild(moon);

// this adds "moon" to the object that had the event-listener added to it
evt.currentTarget.addChild(moon);

// this adds "moon" to "this" (current scope)
addChild(moon);

Sometimes these might be the same, unde other conditions they won't be the same.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .