Accessibility
Trilemtry

Trilemetry, Inc.

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

Exercise 4.2: Extending the event class to pass data in the event object

Introduction

In Exercise 4.1, you learned how to dispatch an event from the Choose component instance and handle it in the main application to make the Preview component instance visible.

In this exercise, you will pass data from the Choose component instance to the Preview component instance (see Figure 1). To accomplish this, you must do more than just create, instantiate, and dispatch an event. To pass data with the event, you must extend the Event type by creating your own ActionScript class to manage the additional data.

Preview the application.

Figure 1. Review your task for this exercise.

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:

Creating an ActionScript class that extends the Event class

You want all of the functionality of the Event class, but you need the ability to store custom data in the event object. In this section, you will create a new ActionScript class that extends the Event class with additional class properties. By extending the Event class, you maintain access to all of its functionality and can add your own properties to store the data.

  1. Download the ex4_02_starter.zip file if you haven't already and extract the file ex4_02_starter.fxp to your computer.
  2. Open Flash Builder.
  3. Import the ex4_02_starter.fxp file.
  4. Open the EmployeePortalAdmin.mxml file.
  5. Run the application.
  6. Click the Preview Button control to display the Preview custom component which contains the Employee of the Month Panel container (see Figure 2). In the last exercise you made the Employee of the Month panel invisible when the application started up and then made it visible only when the user clicked the Preview button in the Choose custom component.

    Click the Preview Button control to display the custom component.

    Figure 2. Click the Preview Button control to display the custom component.

  7. Return to Flash Builder.
  8. Open the Choose.mxml file in the components directory.

    You can see that the Preview button click is handled by the preview_clickHandler() function, which instantiates an event object of the showPreview event type and dispatches it to the main application.

  9. Return to the EmployeePortalAdmin.mxml file and locate the chooseEmployee component instance.

    You can see that the main application handles the showPreview event with the chooseEmployee_showPreviewHandler() event handler, which makes the Preview component instance visible.

  10. In the Package Explorer view, right-click the src folder and select New > Folder (see Figure 3).

    Create a new folder in the Flex project.

    Figure 3. Create a new folder in the Flex project.

  11. In the New Folder dialog box, name the folder events (see Figure 4).

    Name the folder events.

    Figure 4. Name the folder events.

  12. Click Finish.
  13. In the Package Explorer view, right-click the events folder and select New > ActionScript Class (see Figure 5).

    Create a new ActionScript class file.

    Figure 5. Create a new ActionScript class file.

  14. In the New ActionScript Class dialog box, for the Name value, type ShowPreview. Remember that classes are by convention named with an initial capital letter. Do not confuse this class with the showPreview event type defined in the Metadata tag block of the Choose custom component.
  15. Click the Browse button next to the Superclass field.
  16. In the SuperClass dialog box, type event and then select the Event class (see Figure 6).

    Assign the Superclass value to the Event class.

    Figure 6. Assign the Superclass value to the Event class.

  17. Click OK.

    Your New ActionScript Class dialog box should appear as shown in Figure 7.

    Name the new ActionScript class ShowPreview and assign it a Superclass of the flash.events.Event class.

    Figure 7. Name the new ActionScript class ShowPreview and assign it a Superclass of the flash.events.Event class.

  18. Click Finish.

    The ShowPreview.as file opens in the editor. Note that line 5 declares the ShowPreview class and extends the Event class (see Figure 8).

    he ShowPreview class extends the Event class.

    Figure 8. The ShowPreview class extends the Event class.

Adding properties to the class to store the data

In this section, you will declare the properties to be used with the ShowPreview class. Remember that each of these properties are the reason that you are creating an event class. They will hold the data from the Choose custom component. Specifically, they will hold information from the DropDownList control for the selected employee as well as the text that is typed into the congratulatory message TextArea control.

  1. Within the class declaration, but above the ShowPreview() constructor function, declare a public variable named employeeInfo and data type it to the Object class:
    public class ShowPreview extends Event
    {
        public var employeeInfo:Object;
        
        public function ShowPreview(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
        {   
    

    Because the employeeInfo property is an object, it can contain many name-value pairs of data. It will be used to hold all the data for the selected item in the DropDownList control of the Choose component. Remember that the DropDownList control is populated with data from the employees.xml file in the data directory. Although the control's labelField property is set to display only the firstName values from the XML file, remember that lastName, id, title, and all the other nodes in the XML file are also stored as name-value pairs in the DropDownList control.

  2. Below the employeeInfo variable, declare a public variable named message and data type it to the String class:
    public var employeeInfo:Object;
    public var message:String;
    

    The message property of this new class will hold the string data that is typed into the TextArea control of the Choose custom component.

Creating the constructor function and populating the class properties

You just created the properties, but now you must populate them with information.

When an ActionScript class is instantiated using the new keyword, data can be passed to the instance between the parentheses of the constructor. In this section, you will define arguments for the constructor function that will accept data.

  1. From the ShowPreview() constructor and the nested super() method, remove the bubbles and cancelable parameters:
    public function ShowPreview(type:String)
    {
    super(type);
    }
    

    The first argument in the constructor is the name of the event type. Remember that event types that you have already encountered are click and change. In this case, the event type that you will declare is the showPreview event type defined in the Metadata compiler directive.

  2. To the ShowPreview() function, add the employeeInfo and message variables as parameters; be sure to apply the corresponding data type to each:
    public function ShowPreview(type:String, employeeInfo:Object, message:String)
    {
        super(type);
    }
    
  3. Within the ShowPreview() function, below the super() method, assign the employeeInfo and the message constructor arguments as the values for the corresponding class properties:
    public function ShowPreview(type:String,employeeInfo:Object,message:String)
    {
        super(type);
                
        this.employeeInfo = employeeInfo;
                
        this.message = message; 
    }
    

    You use the this keyword before the class properties to distinguish between the class property and the constructor arguments in the assignment.

Overriding the clone() method

The Event class has a clone() method that is only used when you extend the class. In the subclass, in this case ShowPreview, you will use the override keyword to add your own functionality for the clone() method. This function will automatically be called when you instantiate the event and will create the event object with the data.

  1. Below the ShowPreview() constructor, override the clone() method.
    override public function clone():Event
    {
                
    }
    
  2. Within the function, use the return operation to return a new instance of the ShowPreview() function, declaring the type and data properties as arguments.
    override public function clone() : Event
    {
        return new ShowPreview(type, employeeInfo, message);
    }
    
  3. Save the file.

Defining the event type for the extended class

You will no longer be creating an instance of the default flash.events.Event class. You want to instantiate the ShowPreview class that can accept the additional data. In this section, you will adjust the Choose custom component's Metadata compiler directive to include the showPreview event type.

  1. From the Package Explorer view, open the Choose.mxml file.
  2. Locate the MetaData tag set.
  3. To the type parameter of the nested Event() method, change the assigned value to events.ShowPreview:
    <fx:Metadata>
    [Event(name="showPreview", type="events.ShowPreview")]
    </fx:Metadata>

    The ShowPreview class is in the events folder of the Flex project so the class package references that folder. Keep in mind that the showPreview (lowercase s) value is the event type, similar to the click or change event types you've used in other components. ShowPreview (capital S) is the event class.

    In other words, you will be creating an instance of the ShowPreview class and dispatching the showPreview event that will be handled in the main application.

Dispatching the event object with the data

Remember the scenario for this application includes the user choosing a name from the DropDownList control, typing a congratulatory message and then clicking the Preview button.

Currently, when the user clicks the Preview button, the click event is handled by the preview_clickHandler() function, which creates a generic event object that dispatches the showPreview event.

In this section, you will modify the preview_clickHandler() function to create a ShowPreview event object that contains data and that dispatches the showPreview event.

  1. Within the Script block, below the event handlers comment, locate the preview_clickHandler() function:
    protected function preview_clickHandler(event:MouseEvent):void
    {
        var eventObject:Event = new Event("showPreview");
        dispatchEvent(eventObject); 
    }
    
  2. Within the function, change the eventObject variable data type to ShowPreview:
    protected function preview_clickHandler(event:MouseEvent):void
    {
        var eventObject:ShowPreview = new Event("showPreview");
        dispatchEvent(eventObject); 
    }
    
  3. Instantiate the eventObject variable to an instance of the ShowPreview class, passing showPreview as the type parameter, the selected entry from the employeeList DropDownList control as the employeeInfo parameter and the text value of the message TextArea control as the message parameter.

    Note: The employeeList.selectedItem property holds the object data for the currently selected item in the DropDownList control.

    protected function preview_clickHandler(event:MouseEvent):void
    {
        var eventObject:ShowPreview = new ShowPreview("showPreview", employeeList.selectedItem, message.text);
        dispatchEvent(eventObject);
    }
    
  4. Within the Script block, locate the import statements comment.
  5. If the event.ShowPreview package is not present in an import statement, add it below the statement that imports the mx.collections.ArrayCollection package:
    // import statements ----------------------------------------
                
    import mx.collections.ArrayCollection;
                
    import events.ShowPreview;
    

    Note: If you used the Flash Builder code hinting options when you created the ShowPreview event object, then the import statement would have been created automatically.

  6. Save the file.

Handling the event object in the main application

When the user clicks on the Preview button, the data from the DropDownList control and the congratulatory message are now packaged in the event object and dispatched to the main application.

In this section, you will update the showPreview event's handler in the main application to pass the data into the Preview component instance for display in the Employee of the Month panel.

  1. Return to the EmployeePortalAdmin.mxml file.
  2. Within the Script block, locate the chooseEmployee_showPreviewHandler() function.
  3. To the function's arguments, reassign the event parameter to be a data type of the ShowPreview class.
    protected function chooseEmployee_showPreviewHandler(event:ShowPreview):void
    {
        previewEmployeeOfTheMonth.visible = true;
    }
    
  4. Within the function, assign the previewEmployeeOfTheMonth component's employeeInfo property value to event.employeeInfo:
    protected function chooseEmployee_showPreviewHandler(event:ShowPreview):void
    {
        previewEmployeeOfTheMonth.visible = true;
        previewEmployeeOfTheMonth.employeeInfo = event.employeeInfo;
    }
    

    Remember that the Preview custom component expects two properties: employeeInfo and message. Open the Preview.mxml file to see those properties and how they are bound to the UI elements in the Panel container.

  5. Assign the previewEmployeeOfTheMonth component's message property value to event.message:
    protected function chooseEmployee_showPreviewHandler(event:ShowPreview):void
    {
        previewEmployeeOfTheMonth.visible = true;
        previewEmployeeOfTheMonth.employeeInfo = event.employeeInfo;
        previewEmployeeOfTheMonth.message = event.message;
    }
    
  6. Within the Script block, locate the import statements comment.
  7. Below the last import statement, import the events.ShowPreview package:
    // import statements ----------------------------------------
               
    import mx.collections.ArrayCollection;
                
    import mx.rpc.events.ResultEvent;
    
    import events.ShowPreview;
    
  8. Save the file and run the application.
  9. Select an employee from the DropDownList control (see Figure 9).

    Choose an employee.

    Figure 9. Choose an employee.

  10. Type a message to the employee (see Figure 10).

    Type a message to the employee

    Figure 10. Type a message to the employee.

  11. Click the Preview button control.

    You should see the Employee of the Month container appear populated with data (see Figure 11).

    Click the Preview button control to view the employee fo the month

    Figure 11. Click the Preview button control to view the employee of the month.

Test your knowledge

In this exercise, you learned how to extend an ActionScript class and dispatch and handle a custom event.

What is one way to create a new ActionScript class file in Flash Builder?
Select File > New > ActionScript class.
What is the function that is used to assign data to properties within a class is called?
The class constructor function.
Can you pass data in a generic event (an event object created from the flash.events.Event class)?
No.

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.