17
Nov
07

The Event Object

When we use addEventListener() to assign a method or function to handle an event, that method or function receives an event object as its only argument. The event object has a few properties that help us to get information about the event we're handling. The events, such as MouseEvent.CLICK, for example, are nearly self-explanitory. Try running this code snippet in your timeline:

ActionScript 3.0:
  1. var box:Sprite = new Sprite();
  2. box.name = "box";
  3. box.graphics.beginFill(0);
  4. box.graphics.drawRect(0,0,100,100);
  5. box.x = box.y = 50;
  6. addChild(box);
  7.  
  8. box.addEventListener(MouseEvent.CLICK,
  9.                      onClicked,
  10.                      false, 0, true);
  11.  
  12. function onClicked(evt:Event):void {
  13.     trace("type: " + evt.type);
  14.     trace("bubbles: " + evt.bubbles);
  15.     trace("eventPhase: " + evt.eventPhase);
  16.     trace("cancelable: " + evt.cancelable);
  17.    
  18.     trace("target: " + evt.target + " " + evt.target.name);
  19.     trace("currentTarget: " + evt.currentTarget +
  20.           " " + evt.currentTarget.name);
  21. }

After you've pasted this code in your timeline, run your movie and click on the black box. The onClicked function will give you information about the CLICK event in your output window:

type: click
bubbles: true
eventPhase: 2
cancelable: false
target: [object Sprite] box
currentTarget: [object Sprite] box

The type property is a string of the event type. In our example the type is "click"—the string representation of the MouseEvent.CLICK constant. The bubbles property is a boolean that is true when the event bubbles up through the display list and false when it doesn't. The eventPhase property contains an integer representing the phase the event is in at the time the proeprty is queried (1 for capture, 2 for target, 3 for bubble). The cancelable property is a boolean that is true if default behaviors associated with an event can be disabled.

The last two properties are the most commonly used properties of the Event object: target and currentTarget. The target property contains a reference to the display object reached during the "target" phase. For a CLICK event this will normally be whatever display object is directly under the mouse when the CLICK event is triggered. You can see this clearly in the prior "Event Phases in Action" post.

The currentTarget property contains a reference to the display object that is actively processing the event. It's easy to get the target and currentTarget properties mixed up. To make this clearer, let's edit our timeline code slightly to get a better look at the difference. Instead of adding your event to btn, add it to the stage:

Change your addEventListener() method accordingly:

stage.addEventListener(MouseEvent.CLICK,
                       onClicked,
                       false, 0, true);

Now run your movie, click the black box, and take a look at your output window:

type: click
bubbles: true
eventPhase: 3
cancelable: false
target: [object Sprite] box
currentTarget: [object Stage] null

Comparing this to our previous output we can see that the event is no longer getting handled in the "target" phase. Since there is no longer a CLICK event directly associated with btn the event isn't handled until the bubble phase when the CLICK event makes it's way back up to the stage. The currentTarget property reflects this - it shows us that the object processing the event is the stage. This differentiation is important and powerful.


 

Putting Target and Current Target to Use

Now that you've seen the difference between target and currentTarget let's take a look at how we can use them in a real world application. Below is a demo with two draggable windows, each containing a few buttons. The windows and buttons are not functional, but will help demonstrate this concept.

This movie requires Flash Player 9. Please update your player.

Download: Current Target  Download Current Target (7.1 KB, 131 hits)

In the above demo each window is draggable and the clicked window comes to the top of the display list so it appears over the other window. Managing the order in which the windows are drawn is often called z-sorting. Notice that the windows are draggable from any point except when one of the nested buttons is clicked. This feature is made possible by the use of the currentTarget and target properties. A class called SimpleWindow takes care of this functionality:

ActionScript 3.0:
  1. package {
  2.  
  3.     import flash.display.*;
  4.     import flash.events.*;
  5.    
  6.     public class SimpleWindow extends Sprite {
  7.  
  8.         public function SimpleWindow() {
  9.             addEventListener(MouseEvent.MOUSE_DOWN,
  10.                              onWinDown,
  11.                              false, 0, true);
  12.         }
  13.        
  14.         private function onWinDown(evt:MouseEvent):void {
  15.             var win:Sprite = evt.currentTarget as Sprite;
  16.             if (win == evt.target) {
  17.                 win.startDrag();
  18.                 stage.addEventListener(MouseEvent.MOUSE_UP,
  19.                                        onForceStopDrag,
  20.                                        false, 0, true);
  21.             }
  22.             parent.addChild(win);
  23.         }
  24.        
  25.         private function onForceStopDrag(evt:MouseEvent):void {
  26.             stopDrag();
  27.             stage.removeEventListener(MouseEvent.MOUSE_UP,
  28.                                       onForceStopDrag);
  29.         }
  30.     }
  31. }

The trick here is that we know the only time that currentTarget and target are going to be the same is when the user is clicking on the window, not one of the buttons contained within the window. If a button is clicked the target property will reference that button and the currentTarget will reference the window itself. We use a conditional (lines 16 through 21) to make sure the window is dragged only when both the currentTarget and target are the same. Notice that the z-sorting code is outside the conditional. This is because we still want to retain the z-sorting if a button is clicked.

Share This:
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • blogmarks
  • BlogMemes
  • Fark
  • feedmelinks
  • Furl
  • Ma.gnolia
  • Netscape
  • Reddit
  • Slashdot
  • SphereIt
  • Spurl
  • StumbleUpon
  • Technorati
  • YahooMyWeb
  • BlinkList
  • DotNetKicks
  • LinkaGoGo
  • NewsVine
  • blinkbits
  • co.mments
  • MyShare
Print This Post Print This Post

Related Content



2 Responses to “The Event Object”


  1. 1 Rodney Gracia Feb 27th, 2008 at 11:26 pm

    A colleague and I are designing an application that uses drag and drop functionality. The movie clips being dragged have a dynamic text field inside that will be populated programmatically with AS. We have added the listeners that check for MouseDown and MouseUp to the movie clips (parents of the text field). Now we reference the movie clip being dragged in the test functions that start and stop the dragging as "event.target"; we noticed that if the object below the mouse when dragging begins is the movie clip background, not the text field, the dragging works, however, if you happen to click on the dynamic text field and start dragging, the reference to "event.target" generates an error:

    ReferenceError: Error #1069: Property startDrag not found on flash.text.TextField and there is no default value.
    at 00_start_stop_drag_fla::MainTimeline/onStartDrag()
    myMovieClip2

    So even though we are dragging an entire movie clip, because of the way event.target works it fails when the target is the text field inside the MC. This article showed me how to fix that. We use currentTarget instead and the app now works well.

  2. 2 Rich Mar 24th, 2008 at 11:37 am

    Thanks for letting us know about your success, Rodney!

Leave a Reply