In my last article, I wrote about the Flash Delegate, a very useful class that is available as part of the core v2 Flash Components. Another useful class that you'll find among v2 components (and often used with Delegates) is the EventDispatcher.
The EventDispatcher is a class that will mix in event handling capabilities into any other class that you initialize with the EventDispatcher. This will define the methods "addEventListener", "removeEventListener", "dispatchEvent", and "dispatchQueue". Once these methods are defined, your custom class will be able to handle events just like any other prebuilt component.
For example, the following code defines a custom button class that extends a MovieClip and uses EventDistpatcher to initialize its event handling capabilities:
Once the EventDispatcher initializes the class, we can broadcast any event we want by calling the dispatchEvent method. This method takes in one parameter, an object literal that defines the type of event (in this case "click") and a target reference back to the origin of the event. You could also add additional information about the event as additional properties of the object.
To use the CustomButton class, we can create a MovieClip with its linkage identifier and AS 2.0 class as "CustomButton". With an instance of the button on the stage that has an instance name of "myButton", we can use the following code to subscribe to the "click" event of the button and trace out the target to test that our EventDispatcher is working correctly.
It's a quick, cheap and easy way to standardize event handling across all of your classes. You'll never have to deal with _root or this._parent issues again. Combine use of the EventDispatcher with the Delegate and you'll find that your classes will become well structured and rock-solid.
Here are the sample EventDispatcher files from this article including an example of how to use EventDispatcher with a Delegate instead of a direct reference to a method.