O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Accessing the Target Object

During every event dispatch, the Event object passed to every event listener defines a target variable that provides a reference to the target object. Hence, to access the target of an event dispatch, we use the following general event-listener code, which simply outputs the event target's String value during debugging:

public function someListener
 (e:SomeEvent
):void {
  // Access the target of the event dispatch
  trace(e.target);
}

Programs typically use the Event class's instance variable target to control the target object in some way. For example, recall the code we used to respond to the completion of a file-load operation (shown in Example 12-1):

package {
  import flash.display.*;
  import flash.net.*;
  import flash.events.*;

  public class FileLoader extends Sprite {
    public function FileLoader () {
      var urlLoader:URLLoader = new URLLoader();
      urlLoader.addEventListener(Event.COMPLETE, completeListener);
      urlLoader.load(new URLRequest("someFile.txt"));
    }

    private function completeListener (e:Event):void {
      trace("Load complete");
    }
  }
}

In the preceding code, within the completeListener( ) function, we might want to access the urlLoader object in order to retrieve the content of the loaded file. Here's the code we'd use (notice that, for added type safety, we cast target to URLLoader—the actual datatype of the target object):

private function completeListener (e:Event):void {
  var loadedText:String = URLLoader(e.target).data;
}

After the preceding code runs, loadedText ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required