User Guide

Event listeners 361
}
}
}
import flash.display.Sprite;
import flash.events.MouseEvent;
class ChildSprite extends Sprite
{
public function ChildSprite()
{
graphics.beginFill(0xFF0000);
graphics.drawRect(0,0,100,100);
graphics.endFill();
addEventListener(MouseEvent.CLICK, myListenerObj.clickHandler);
}
}
var myListenerObj:Object = new Object();
myListenerObj.clickHandler = function (event:MouseEvent):void
{
trace("clickHandler detected an event of type: " + event.type);
trace("the this keyword refers to: " + this);
}
The results of the trace will look like this:
clickHandler detected an event of type: click
the this keyword refers to: [object global]
You would expect that this would refer to myListenerObj and that the trace output would
be
[object Object], but instead it refers to the global object. When you pass in a dynamic
property name as an argument to
addEventListener(), Flash Player is unable to create a
bound method. This is because what you are passing as the
listener parameter is nothing
more than the memory address of your listener function, and Flash Player has no way to link
that memory address with the
myListenerObj instance.
Managing event listeners
You can manage your listener functions using the methods of the IEventDispatcher interface.
The IEventDispatcher interface is the ActionScript 3.0 version of the EventTarget interface of
the DOM event model. Although the name IEventDispatcher may seem to imply that its
main purpose is to send (or dispatch) event objects, the methods of this class are actually used
much more frequently to register event listeners, check for event listeners, and remove event
listeners. The IEventDispatcher interface defines five methods, as shown in the following
code:
package flash.events