Handling events

Flex applications are event driven. Events let a programmer know when the user has interacted with an interface component, and also when important changes have happened in the appearance or life cycle of a component, such as the creation or destruction of a component or its resizing.

When an instance of a component dispatches an event, objects that have registered as listeners for that event are notified. You define event listeners, also called event handlers, in ActionScript to process events. You register event listeners for events either in the MXML declaration for the component or in ActionScript. For additional examples of the event handling, see Using components in MXML and ActionScript.

The following example registers an event listener in MXML that is processed when you change views in an Accordion container.

<?xml version="1.0"?>
<!-- components\CompIntroEvent.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" 
    width="300"
    height="280">

    <fx:Script>
        <![CDATA[
            import mx.controls.Alert;
            private function handleAccChange():void {
                Alert.show("You just changed views.");
            }
        ]]>
    </fx:Script>

    <!-- The Accordion container dispatches a change event when the 
            selected child container changes. -->
    <mx:Accordion id="myAcc" 
        height="60" 
        width="200" 
        change="handleAccChange();">
        <s:NavigatorContent label="Box 1">
            <s:Label text="This is one view."/>
        </s:NavigatorContent>

        <s:NavigatorContent label="Box 2">
            <s:Label text="This is another view."/>
        </s:NavigatorContent>
    </mx:Accordion>
</s:Application>

The executing SWF file for the previous example is shown below:

You can pass an event object, which contains information about the event, from the component to the event listener.

For the Accordion container, the event object passed to the event listener for the change event is of class IndexChangedEvent. You can write your event listener to access the event object, as the following example shows:

<?xml version="1.0"?>
<!-- components\CompIntroEventAcc.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" 
    width="300"
    height="280">

    <fx:Script>
        <![CDATA[
            // Import the class that defines the event object.
            import mx.events.IndexChangedEvent;
            import mx.controls.Alert;
            
            private function handleChange(event:IndexChangedEvent):void {
                var currentIndex:int=event.newIndex;
                Alert.show("You just changed views.\nThe new index is "
                    + event.newIndex + ".");
            }
        ]]>
    </fx:Script>

    <!-- The Accordion control dispatches a change event when the 
            selected child container changes. -->
    <mx:Accordion id="myAcc" 
        height="60" 
        width="200" 
        change="handleChange(event);">
        <s:NavigatorContent label="Box 1">
            <s:Label text="This is one view."/>
        </s:NavigatorContent>

        <s:NavigatorContent label="Box 2">
            <s:Label text="This is another view."/>
        </s:NavigatorContent>
    </mx:Accordion>
</s:Application>

The executing SWF file for the previous example is shown below:

In this example, you access the newIndex property of the IndexChangedEvent object to determine the index of the new child of the Accordion container. For more information on events, see Events.

About the component instantiation life cycle

The component instantiation life cycle describes the sequence of steps that occur when you create a component object from a component class. As part of that life cycle, Flex automatically calls component methods, dispatches events, and makes the component visible.

The following example creates a Button control in ActionScript and adds it to a Group container:

// Create a Group container. 
var groupContainer:Group = new Group(); 
// Configure the Group container.  
groupContainer.x = 10; 
groupContainer.y = 10; 
 
// Create a Button control.  
var b:Button = new Button() 
// Configure the button control. 
b.label = "Submit"; 
... 
// Add the Button control to the Box container. 
groupContainer.addElement(b);

The following steps show what occurs when you execute the code to create the Button control, and add the control to the container:

  1. You call the component’s constructor, as the following code shows:

    // Create a Button control.  
    var b:Button = new Button()
  2. You configure the component by setting its properties, as the following code shows:

    // Configure the button control. 
    b.label = "Submit";
  3. You call the addElement() method to add the component to its parent, as the following code shows:

    // Add the Button control to the Box container. 
    groupContainer.addElement(b);

    Flex then performs the following actions:

  4. Sets the parent property for the component to reference its parent container.

  5. Computes the style settings for the component.

  6. Dispatches the preinitialize event on the component. The component is in a very raw state when this event is dispatched. Many components, such as the Button control, create internal child components to implement functionality. When Flex dispatches the preinitialize event, the children (including the internal children, of a component) have not yet been created.

  7. Dispatches the initialize event on the component. At this time, all of the component’s children are initialized, but the component has not been sized or processed for layout. You can use this event to perform additional processing of the component before it is laid out.

    Because the initialize event is dispatched early in the component's startup sequence, make sure that none of your processing causes the component to invalidate itself. You typically perform any final processing during the creationComplete event.

  8. Dispatches the childAdd event on the parent container.

  9. Dispatches the initialize event on the parent container.

  10. To display the application, a render event gets triggered, and Flex does the following:

    1. Flex completes all processing required to display the component, including laying out the component.

    2. Makes the component visible by setting the visible property to true.

    3. Dispatches the creationComplete event on the component. The component is sized and processed for layout. This event is only dispatched once when the component is created.

    4. Dispatches the updateComplete event on the component. Flex dispatches additional updateComplete events whenever the layout, position, size, or other visual characteristic of the component changes and the component is updated for display.

You can later remove a component from a container by using the removeElement() method. The removed child’s parent property is set to null. If you add the removed child to another container, it retains its last known state. If there are no references to the component, it is eventually deleted from memory by the garbage collection mechanism of Adobe® Flash® Player.

Given this sequence of actions, you should use the events as follows:

  • The preinitialize event occurs too early in the component life cycle for most initialization activities. It is useful, however, in the rare situations where you must set the properties on a parent before the children are created.

  • To configure a component before Flex has determined its visual appearance, use the initialize event. For example, use this for setting properties that affect its appearance, height, or width.

  • Use the creationComplete event for actions that rely on accurate values for the component’s size or position when the component is created. If you use this event to perform an action that changes the visual appearance of the component, Flex must recalculate its layout, which adds unnecessary processing overhead to your application.

  • Use the updateComplete event for actions that must be performed each time a component’s characteristics change, not just when the component is created.