Accessibility
Trilemtry

Trilemetry, Inc.

Created:
2 November 2009
User Level:
All
Products:
Flex

Exercise 4.1: Creating an event and dispatching the event object

In this exercise, you will create an application that lets an administrator choose an employee to feature on the Employee of the Month panel of the Employee Portal.

The application involves two custom components: one to choose the employee and write a congratulatory message and the other to preview how the Employee of the Month panel will appear on the Employee Portal (see Figure 1).

Preview the application.

Figure 1. Review your task for this exercise.

The Preview custom component will initially be invisible. When the user clicks the Preview button in the Choose custom component, an event is dispatched to the main application that will make the Preview component visible.

In the next exercise, you will populate the Preview component with data from the Choose component.

In this exercise, you will learn how to:

Requirements

In order to complete this tutorial, you need the following software and files:

Flash Builder 4

Exercise files

Prerequisite knowledge:

Create an event type for the Event class

You have used many event types in this video training series. For example, you have used the click event type for a Button control and the change event for the DropDownList control.

Remember that the Flex framework classes can be modified and extended for your application needs. In this section you will create your own showPreview event type within the Choose custom component.

  1. Download the ex4_01_starter.zip file if you haven't already and extract the file ex4_01_starter.fxp to your computer.
  2. Open Flash Builder.
  3. Import the ex4_01_starter.fxp file.
  4. Open the EmployeePortalAdmin.mxml file.
  5. Run the application.

    You should see the application as shown in Figure 2. The DropDownList control is populated with XML data and you can type a message into the TextArea control. The Employee of the Month panel does not show any content and nothing happens yet when you click the Preview button.

    Run the application to see its contents

    Figure 2. Run the application to see its contents.

  6. Return to the EmployeePortalAdmin.mxml file in Flash Builder.

    You can see that the main application file defines an HTTPService call to retrieve data from the employees.xml file in the data folder and then populates a class property named employeeData with the returned data. The employeeData object is then passed to the chooseEmployee instance of the Choose custom component, which then binds the data to the DropDownList control.

    The Preview.mxml custom component expects two properties: employeeInfo and message. The values of these properties are bound to the image and text controls in the component. However, since this data is not yet provided, the display appears empty.

  7. Locate the Preview custom component instance in the EmployeePortalAdmin.mxml main application code:
    <s:HGroup gap="30">
    
    <components:Choose id="chooseEmployee"
    employeeData="{employeeData}"
    x="30" y="90"/>
    
    <components:Preview id="previewEmployeeOfTheMonth"
    title="Employee of the Month"
    x="250" y="90"
    width="250"/>
    
    </s:HGroup>
    
  8. To the components:Preview tag, assign the visible property value to false:
    <components:Preview id="previewEmployeeOfTheMonth"
    title="Employee of the Month"
    x="250" y="90"
    width="250" 
    visible="false"/>
    

    This code will make the Preview instance invisible at application start-up. The event that you will create, dispatch, and handle in the rest of this exercise will make the Preview instance visible again.

  9. Save the file.
  10. From the Package Explorer view, open the Choose.mxml file in the components directory.
  11. Locate the Metadata comment
  12. Below the comment, create a Metadata tag block.
    <!-- Metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    
    <fx:Metadata>
    
    </fx:Metadata>
  13. Within the Metadata tag block, use the Event directive to name a new event type for the flash.events.Event class. Name the event type showPreview.
    <fx:Metadata>
    [Event(name="showPreview", type="flash.events.Event")]
    </fx:Metadata>
    

    Keep in mind that this is an arbitrary name that you have created for your custom component event. In other words, you've created your own event type for the built-in Event class.

    The Metadata tag is a compiler directive that registers this new event type with Flash Builder. If you save Choose.mxml and return to the main application file and use code hinting to see the properties, methods, and events in the component instance, you would now see the showPreview event listed.

Instantiating and dispatching the event to the main application

The application scenario includes the administrator selecting an employee from the DropDownList control in the Choose custom component instance, typing a congratulatory message to the user, and then clicking the Preview button. This means that you must handle the click event on the Preview button.

When a user clicks the Preview button, you will handle the click event by creating an instance of the event object you defined in the Metadata compiler directive and then dispatching the event to the main application using the dispatch() method of the Event class.

  1. In the Choose.mxml file, locate the Button control with the id property value assigned to preview.
  2. To the Button control, use the code lookup window to add a click event property (see Figure 3).

    event for the Button control

    Figure 3. Generate a click event for the Button control.

  3. Using code lookup to generate the click event will present you with the Generate Click Handler option in the code lookup window (see Figure 4). Click the option or press the Enter key to use the option to generate a function.

    Generate a click handler function

    Figure 4. Generate a click handler function.

  4. Within the Script tag block, below the event handlers comment, locate the generated preview_clickHandler() function:
    // event handlers -------------------------------------------
    protected function preview_clickHandler(event:MouseEvent):void
      {
      // TODO Auto-generated method stub
      }
     

    Remember that generated event handlers are named first by the object's id value (in this case preview), then the event type (in this case click), and then the word Handler.

    Handling the click event is not the learning point of this exercise. You have created and handled many events already in the course of this video training series. The learning point follows: You will create an event object and dispatch it.

  5. Within the preview_clickHandler() function, delete the generated stub comment and declare a variable named eventObject and data type it to the Event class.
    protected function preview_clickHandler(event:MouseEvent):void
    {
         var eventObject:Event
    }
    

    Note: The name of this event object, eventObject, is arbitrary. Remember, though, that it is an instance of the Event class.

  6. Instantiate eventObject using the new keyword and assign it to the showPreview event type that you named in the Metadata tag block.
    protected function preview_clickHandler(event:MouseEvent):void
    {
         var eventObject:Event = new Event("showPreview");
    }
    

    You have just created an event object that is typed to your own showPreview event type. You do not need to import the Event class.

  7. Within the preview_clickHandler() function, below the eventObject variable instantiation, use the dispatchEvent() method to dispatch eventObject.
    protected function preview_clickHandler(event:MouseEvent):void
    {
        var eventObject:Event = new Event("showPreview");
        dispatchEvent(eventObject); 
    }
    

    The dispatchEvent() method dispatches the event object to the main application. You will handle the event in the main application file next.

  8. Save the file.

Handling the event in the main application

In this section, you will create an event handler function to handle a dispatch of the showPreview event within the main application file.

  1. Open the EmployeePortalAdmin.mxml file.
  2. Locate the HGroup container that nests the Choose and Preview components tags.
    <s:HGroup gap="30"> 
    
    <components:Choose id="chooseEmployee"
    employeeData="{employeeData}"
    x="30" y="90"/>
    
    <components:Preview id="previewEmployeeOfTheMonth"
    title="Employee of the Month"
    x="250" y="90"
    width="250"
    visible="false"/>
    
    </s:HGroup>
    

    You can see that the Choose and Preview instances are named chooseEmployee and previewEmployeeOfTheMonth, respectively.

  3. On the components:Choose tag, use the code lookup tool to add the showPreview event (see Figure 5).

    Generate the showPreview event

    Figure 5. Generate the showPreview event.

    The Metadata compiler directive has directed Flash Builder to treat the showPreview event type that you created as any other event of the Choose component.

  4. Using code lookup to generate the showPreview event will present you with the Generate Click Handler option, within the code lookup window (see Figure 6). Select the option or press Enter to generate the function.

    Generate the event handler function

    Figure 6. Generate the event handler function

  5. Within the Script block, below the event handlers comment, locate the generated chooseEmployee_showPreviewHandler() function:
    protected function chooseEmployee_showPreviewHandler(event:Event):void
    {
         // TODO Auto-generated method stub
    }
    
  6. Within the chooseEmployee_showPreviewHandler() function, delete the generated stub code and assign the previewEmployeeOfTheMonth Preview custom component's visible property to true:
    protected function chooseEmployee_showPreviewHandler(event:Event):void
    {
        previewEmployeeOfTheMonth.visible = true;
    }
    

    You have just dispatched the showPreview event from the Choose component and handled it in the main application in the chooseEmployee_showPreviewHandler() event handler.

  7. Save the file.
  8. Run the application.

    Note that the Employee of the Month panel container is not visible (see Figure 7).

    Run the application and note that the Employee of the Month Panel container is not visible

    Figure 7. Run the application and note that the Employee of the Month panel container is not visible.

  9. Click the Preview Button control.

    The Employee of the Month panel container is now visible (see Figure 8).

    Click the Preview button control to display the custom component

    Figure 8. Click the Preview button control to display the custom component.

Test your knowledge

In this exercise, you learned how to create and trigger an event, dispatch it to the main application, and handle the event.

How do you create a new event type for the Event class?
Create a Metadata tag block and define the new event type in the Event declaration referencing the flash.events.Event class.
How is the new event type handled differently in the main application file than other built-in event types of the Flex framework?
It is not handled differently.

About the author

Trilemetry, Inc is a development and education organization that implements a human-centered design approach to the creation of software and content. Their Adobe portfolio includes the Adobe ColdFusion Getting Started Experience, the Adobe Flex Getting Started Experience, the Flex in a Week video series, the official Adobe instructor-led training course Flex 3: Extending and Styling Components and more. They also create and support many Web applications from interactive Flash sites and corporate web sites to mission-critical business applications.