User Guide

38 Creating Custom Events
Dispatching custom events
Flex defines many of the most common events, such as the click event for the Button
control, however, your application may require that you create events. In your custom Flex
components, you can dispatch any of the predefined events inherited by the component from
its superclass, and dispatch new events that you define within the component.
To dispatch a new event from your custom component, you must do the following:
1. (Optional) Create a subclass from the flash.events.Event class to create an event class that
describes the event object. For more information, see “Creating a subclass from the Event
class” on page 38.
2. (Optional) Use the [Event] metadata tag to make the event public so that the MXML
compiler recognizes it. For more information, see “Using the Event metadata tag”
on page 40.
3. Dispatch the event using the dispatchEvent() method. For more information, see
“Dispatching an event” on page 41.
Creating a subclass from the Event class
All events use an event object to transmit information about the event to the event listener,
where the base class for all event objects is the flash.events.Event class. When you define a
custom event, you can dispatch an event object of type Event, or you can create a subclass of
the Event class to dispatch an event object of a different type. You typically create a subclass of
the Event class when your event requires you to add information to the event object, such as a
new property to hold information that the event listener requires.
For example, the event objects associated with the Flex Tr e e control include a property named
node, which identifies the node of the Tree control associated with the event. To support the
node property, the Tree control dispatches event objects of type TreeEvent, a subclass of the
Event class.
Within your subclass of the Event class, you can add properties, add methods, set the value of
an inherited property, or override methods inherited from the Event class. For example, you
might want to set the
bubbles property to true to override the default setting of false,
which is inherited from the Event class.
You are required to override the
Event.clone() method in your subclass. The clone()
method returns a cloned copy of the event object by setting the
type property and any new
properties in the clone. Typically, you define the
clone() method to return an event instance
created with the
new operator.