Dispatching a custom event

There are many common events for Flex components, such as the click or change events. These events are very usefull and great for many situations. Your application or custom component may require more from an event than is provided in these built-in events. Not a problem! You can dispatch any of the predefined events inherited by a component’s superclass, as well as new, custom, events that you define within the component.

To dispatch a new event from your custom component, you must do the following:

  1. Create a subclass from the flash.events.Event class (or another event class) to create an event class that describes the event object. This step is optional.[as]
    public class MyCustomEvent extends Event
    {
    static public var customEventName:String = “customEventName”; public var myEventData:*;

    public function MyCustomEvent(type:String, p_eventData:*, bubbles:Boolean=false, cancelable:Boolean=false)
    {
    super(type, bubbles, cancelable);

    myEventData = p_eventData;
    }

    }
    [/as]

  2. Use the [Event] metadata tag to make the event public so that the MXML compiler recognizes it. This step is optional.
    [as]
    [Event(name=”customEventName”, type=”com.events.MyCustomEvent”)]
    public class MyCustomEvent extends Event
    { …[/as]
  3. Dispatch the event using the dispatchEvent() method.
    [as]
    dispatchEvent(new MyCustomEvent(MyCustomEvent.customEventName, eventData));
    [/as]

[Simple Custom Event Sample]

[Simple Custom Event Source]

Flex Doumentation:

Leave a Reply

Your email address will not be published. Required fields are marked *