You can create custom events as part of defining MXML and ActionScript components. Custom events let you add functionality to your custom components to respond to user interactions, to trigger actions by your custom component, and to take advantage of data binding.
For more information on creating custom events for MXML components, see Advanced MXML components. For information on creating custom events for ActionScript components, see Create simple visual components in ActionScript.
Flex applications are event-driven. Events let an application know when the user interacts with the interface, and also when important changes happen in the appearance or life cycle of a component, such as the creation of a component or its resizing. Events can be generated by user input devices, such as the mouse and keyboard, or by the asynchronous operations, such as the return of a web service call or the firing of a timer.
The core class of the Flex component architecture, mx.core.UIComponent, defines core events, such as updateComplete, resize, move, creationComplete, and others that are fundamental to all components. Subclasses of UIComponent inherit these events.
Custom components that extend existing Flex classes inherit all the events of the base class. Therefore, if you extend the Button class to create the MyButton class, you can use the click event and the events that all controls inherit, such as mouseOver or initialize, as the following example shows:
<?xml version="1.0"?>
<!-- createcomps_events/EventsMyApplication.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:MyComp="myComponents.*">
<fx:Script>
<![CDATA[
import flash.events.Event;
// Event listener for the click event.
private function handleClick(eventObj:Event):void {
// Define event listener.
}
// Event listener for the initialize event.
private function handleInit(eventObj:Event):void {
// Define event listener.
}
]]>
</fx:Script>
<MyComp:MyButton
click="handleClick(event);"
initialize="handleInit(event);"/>
</s:Application>
In addition to using the events inherited from its superclasses, your custom components can define custom events. You use custom events to support data binding, to respond to user interactions, or to trigger actions by your component.
For more information on the Flex event mechanism, see Events.
When a Flex component dispatches an event, it creates an event object, where the properties of the event object contain information describing the event. An event listener takes this event object as an argument and accesses the properties of the object to determine information about the event.
The base class for all event objects is the flash.events.Event class. All event objects are instances of the Event class, or instances of a subclass of the Event class.
The following table describes the public properties of the Event class. The Event class implements these properties using getter methods.
|
Property |
Type |
Description |
|---|---|---|
type |
String |
The name of the event; for example, "click". The event constructor sets this property. |
target |
EventDispatcher |
A reference to the component instance that dispatches the event. This property is set by the dispatchEvent() method; you cannot change this to a different object. |
currentTarget |
EventDispatcher |
A reference to the component instance that is actively processing the Event object. The value of this property is different from the value of the target property during the event capture and bubbling phase. For more information, see Events. |
eventPhase |
uint |
The current phase in the event flow. The property might contain the following values:
|
bubbles |
Boolean |
Whether an event is a bubbling event. If the event can bubble, the value for this property is true; otherwise, it is false. You can optionally pass this property as a constructor argument to the Event class. By default, most event classes set this property to false. For more information, see Events. |
cancelable |
Boolean |
Whether the event can be canceled. If the event can be canceled, the value for this value is true; otherwise, it is false. You can optionally pass this property as a constructor argument to the Event class. By default, most event classes set this property to false. For more information, see 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:
(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.
(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.
Dispatch the event using the dispatchEvent() method. For more information, see Dispatching an event.
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 the Event type, 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 Tree 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.
Suppose that you want to pass information about the state of your component to the event listener as part of the event object. To do so, you create a subclass of the Event class to create an event, EnableChangeEvent, as the following example shows:
package myEvents
{
//createcomps_events/myEvents/EnableChangeEvent.as
import flash.events.Event;
public class EnableChangeEvent extends Event
{
// Public constructor.
public function EnableChangeEvent(type:String,
isEnabled:Boolean=false) {
// Call the constructor of the superclass.
super(type);
// Set the new property.
this.isEnabled = isEnabled;
}
// Define static constant.
public static const ENABLE_CHANGE:String = "enableChange";
// Define a public variable to hold the state of the enable property.
public var isEnabled:Boolean;
// Override the inherited clone() method.
override public function clone():Event {
return new EnableChangeEvent(type, isEnabled);
}
}
}
In this example, your custom class defines a public constructor that takes two arguments:
A String value that contains the value of the type property of the Event object.
An optional Boolean value that contains the state of the component's isEnabled property. By convention, all constructor arguments for class properties, except for the type argument, are optional.
From within the body of your constructor, you call the super() method to initialize the base class properties.
You use the [Event] metadata tag to define events dispatched by a component so that the Flex compiler can recognize them as MXML tag attributes in an MXML file. You add the [Event] metadata tag in one of the following locations:
ActionScript components
Above the class definition, but within the package definition, so that the events are bound to the class and not a particular member of the class.
MXML components
In the <fx:Metadata> tag of an MXML file.
The Event metadata keyword has the following syntax:
[Event(name="eventName", type="package.eventType")]
The eventName argument specifies the name of the event. The eventType argument specifies the class name, including the package, that defines the event object.
The following example identifies the enableChange event as an event that an ActionScript component can dispatch:
[Event(name="enableChange", type="myEvents.EnableChangeEvent")]
public class MyComponent extends TextArea
{
...
}
The following example shows the [Event] metadata tag within the <fx:Metadata> tag of an MXML file:
<?xml version="1.0"?>
<!-- createcomps_events\myComponents\MyButton.mxml -->
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
click="dispatchEvent(new EnableChangeEvent('enableChange'));">
<fx:Script>
<![CDATA[
import myEvents.EnableChangeEvent;
]]>
</fx:Script>
<fx:Metadata>
[Event(name="enableChange", type="myEvents.EnableChangeEvent")]
</fx:Metadata>
</s:Button>
Once you define the event using the [Event] metadata tag, you can refer to the event in an MXML file, as the following example shows:
<?xml version="1.0"?>
<!-- createcomps_events/MainEventApp.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns:MyComp="myComponents.*" >
<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import myEvents.EnableChangeEvent;
public function
enableChangeListener(eventObj:EnableChangeEvent):void {
// Handle event.
myTA2.text='got event';
}
]]>
</fx:Script>
<MyComp:MyButton enableChange="myTA.text='got event';" />
<mx:TextArea id="myTA" />
<MyComp:MyButton enableChange="enableChangeListener(event);" />
<mx:TextArea id="myTA2" />
</s:Application>
If you do not identify an event with the [Event] metadata tag, the compiler generates an error if you try to use the event name in MXML. The metadata for events is inherited from the superclass, however, so you do not need to tag events that are already defined with the [Event] metadata tag in the superclass.
You use the dispatchEvent() method to dispatch an event. The dispatchEvent() method has the following signature:
public dispatchEvent(event:Event):Boolean
This method requires an argument of the Event type, which is the event object. The dispatchEvent() method initializes the target property of the event object with a reference to the component dispatching the event.
You can create an event object and dispatch the event in a single statement, as the following example shows:
dispatchEvent(new Event("click"));
You can also create an event object, initialize it, and then dispatch it, as the following example shows:
var eventObj:EnableChangeEvent = new EnableChangeEvent("enableChange");
eventObj.isEnabled=true;
dispatchEvent(eventObj);
For complete examples that create and dispatch custom events, see Advanced MXML components and Create simple visual components in ActionScript.
The constructor of an event class typically takes a single required argument that specifies the value of the event object's type property. In the previous section, you passed the string enableChange to the constructor, as the following example shows:
// Define event object, initialize it, then dispatch it.
var eventObj:EnableChangeEvent = new EnableChangeEvent("enableChange");
dispatchEvent(eventObj);
The Flex compiler does not examine the string passed to the constructor to determine if it is valid. Therefore, the following code compiles, even though enableChangeAgain might not be a valid value for the type property:
var eventObj:EnableChangeEvent =
new EnableChangeEvent("enableChangeAgain");
Because the compiler does not check the value of the type property, the only time that your application can determine if enableChangeAgain is valid is at run time.
However, to ensure that the value of the type property is valid at compile time, Flex event classes define static constants for the possible values for the type property. For example, the Flex EffectEvent class defines the following static constant:
// Define static constant for event type. public static const EFFECT_END:String = "effectEnd";
To create an instance of an EffectEvent class, you use the following constructor:
var eventObj:EffectEvent = new EffectEvent(EffectEvent.EFFECT_END);
If you incorrectly reference the constant in the constructor, the compiler generates a syntax error because it cannot locate the associated constant. For example, the following constructor generates a syntax error at compile time because MY_EFFECT_END is not a predefined constant of the EffectEvent class:
var eventObj:EffectEvent = new EffectEvent(EffectEvent.MY_EFFECT_END);
You can use this technique when you define your event classes. The following example modifies the definition of the EnableChangeEventConst class to include a static constant for the type property:
package myEvents
{
//createcomps_events/myEvents/EnableChangeEventConst.as
import flash.events.Event;
public class EnableChangeEventConst extends Event
{
// Public constructor.
public function EnableChangeEventConst(type:String,
isEnabled:Boolean=false) {
// Call the constructor of the superclass.
super(type);
// Set the new property.
this.isEnabled = isEnabled;
}
// Define static constant.
public static const ENABLE_CHANGE:String = "myEnable";
// Define a public variable to hold the state of the enable property.
public var isEnabled:Boolean;
// Override the inherited clone() method.
override public function clone():Event {
return new EnableChangeEvent(type, isEnabled);
}
}
}
Now you create an instance of the class by using the static constant, as the following example shows for the MyButtonConst custom component:
<?xml version="1.0"?>
<!-- createcomps_events\myComponents\MyButtonConst.mxml -->
<s:Button xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
click="dispatchEvent(new EnableChangeEventConst(EnableChangeEventConst.ENABLE_CHANGE));">
<fx:Script>
<![CDATA[
import myEvents.EnableChangeEventConst;
]]>
</fx:Script>
<fx:Metadata>
[Event(name="myEnable", type="myEvents.EnableChangeEventConst")]
</fx:Metadata>
</s:Button>
This technique does not preclude you from passing a string to the constructor.
Navigation
Adobe and Adobe Flash Platform are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries and are used by permission from Adobe. No other license to the Adobe trademarks are granted.