Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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();
}
share|improve this question
    
"...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. –  Byte56 Aug 26 '12 at 16:43
add comment

1 Answer

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.