Functions as Event Handlers
Functions often provide a better way to handle events. Some examples of functions as event handlers are used in Chapter 3. Having a function be called when an event occurs is easy:
- Define the function in an Script block.
- Assign the function call as the value of whatever event property in the MXML component.
This approach does a better job of separating your presentation from your logic, allows you to handle events in a more sophisticated manner, and will also let you use the same function to handle all sorts of events on all sorts of components.
Creating Simple Event Handlers
If you want to create an application that only displays an image if a box is checked (Figures 4.8 and 4.9), you can start by defining the components:
<s:CheckBox id="showImageCheckBox" label="Show Image?" change="showHideImage();" /> <mx:Image id="myImage" source="@Embed('assets/trixie.jpg')" visible="false" />
The checkbox has an id value of showImageCheckBox and, when changed, calls the showHideImage() function. You’ll notice that I’m referencing the change event here, because I want function to be called whenever the checkbox’s status changes, whether that means the user just checked or unchecked it.
The image has an id of myImage and its source property will embed the image file at compilation, using a relative path to the image. The image itself is initially invisible (its visible property is false), meaning it’s part of the application but not seen. (In fact, it could even affect the layout while invisible).
Within the Script tags, the showHideImage() needs to be defined:
private function showHideImage():void { // Actually functionality. }
The function takes no arguments and returns no values. Within the function, the image’s visibility should toggle depending upon whether the checkbox is selected or not. A simple conditional takes care of that:
if (showImageCheckBox.selected == true) { myImage.visible = true; } else { myImage.visible = false; }
And that’s all there is to it: check the box and the image appears, uncheck it and the image disappears.
Sending Values to Event Handlers
Event handling functions can also be written so that they take arguments, just like any function. The value then needs to be passed when the function is called. To do so, you would write that into the component. Here are two RadioButtons, each of which calls the same function but sends a different Boolean value to it:
<s:RadioButton label="show" click="showHideImage(true);" /> <s:RadioButton label="hide" click="showHideImage(false);" />
And here is that function definition:
private function showHideImage(visible:Boolean):void { myImage.visible = visible; }
The function takes one parameter, of type Boolean. Inside the function, the image’s visible property is assigned the value passed to the function.
Sending Events to Functions
It’s probably not obvious why, offhand, but the most likely value you’ll want to send to an event handling function would be an event object. To do so, just define the function call so that it sends along the event variable:
<s:Button text="Click Here!" click="myEventHandler(event);" />
Then you write the function so that it takes an argument of type Event:
private function myEventHandler(event:Event):void { // Actually functionality. }
By convention, the parameter is named event or just e.
Within the function, you can make use of the event object’s properties and methods. This includes type, currentTarget, eventPhase, and so forth. Most importantly, you can access the object that trigged the event by referencing event.target. Any of the target object’s available properties and methods are then accessible using event.target.whatever. For example, here’s another way of writing the moveMe() function (for moving a component):
private function moveMe(event:Event):void { event.target.x += 10; }
Instead of hardcoding the component’s id value in the function, you can refer to the id value of event.target, where target represents the object that triggered the event. There may be no apparent benefit to this approach, but now that same function can be used on any number of components without a knowledge of what those components are (so long as they have an x property):
<s:Button id="myButton" x="20" y="20" click="moveMe(event);" label="Click Me!" /> <s:Label id="myLabel" x="20" y="120" click="moveMe(event);" text="Click Me!" /> <mx:Image id="myImage" x="20" y="220" click="moveMe(event);" source="@Embed('assets/image.png')" />
Taking this a step further, you could call the same function when any member of the group is clicked:
<s:Group click="moveMe(event);"> <s:Button id="myButton" x="20" y="20" label="Click Me!" /> <s:Label id="myLabel" x="20" y="50" text="Click Me!" /> <mx:Image id="myImage" x="20" y="70" source="@Embed('assets/image.png')" /> </s:Group>
Now the same function call applies to the click event in all four objects (clicking anywhere in the group but not on one of the children moves the entire group over ten pixels). Figure 4.10 shows the application as it originally displays; Figure 4.11 shows it after multiple clicks.
Before going further, let’s take this information and create a utility for reporting upon what events were triggered by what components. Doing so will better demonstrate the event flow.
- Create a new Flex project for the Web.
- In the Application tag, associate the reportOnEvent() function with any click.
- Within a Script block, define the function.
- Define the components.
- Save, compile, and run the application.
- Click on the various components, and not on any components at all, to see the results (Figure 4.13).
- Add click event handlers to the VGroup, Label, and RichText components.
- Save, compile, and run the application.
- Click on the various components, and not on any components, to see the results (Figure 4.14).
<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" click="reportOnEvent(event);">
By assigning this event handler in the Application tag, the reportOnEvent() function will be called when the user clicks anywhere in the application. The function is passed an event object.
<fx:Script><![CDATA[ private function reportOnEvent(event:Event):void { results.text += "Target: " + event.target.id + "\ncurrentTarget: " + event.currentTarget.id + "\nPhase: " + event.eventPhase + "\n----------\n"; } ]]></fx:Script>
The function expects one argument of type Event. Within the function, the text property of the results component will be updated. This will be a RichText component, added in the next step. Each call of this function will concatenate several strings and values to the current value of the text property. Those strings are: Target:, followed by a space; the id value of target; a newline (\n, which will space the output over multiple lines), currentTarget:, followed by a space; the id value of the currentTarget property; another newline, followed by Phase: and a space; the eventPhase, which will be the number 1, 2, or 3; and a newline, followed by several dashes, and another newline. If you’re at all confused about how this will look, take a peak at the next three figures in the book.
<s:VGroup id="myVGroup" paddingLeft="10" paddingTop="10"> <s:Label id="myLabel" text="Click on Me!" /> <s:Panel title="Results"> <s:RichText id="results" /> </s:Panel> </s:VGroup>
To best demonstrate what’s going on, I want to add a couple of components, so I started with a Label inside of a VGroup. To display the results, I added a RichText component within a Panel, also in the VGroup. Figure 4.12 shows the application when first loaded.
The figure shows the results after clicking upon the VGroup first (I clicked to the left of the Panel), clicking the Label next, the body of the Panel (i.e., the RichText component) after that, and, finally, outside of any component. You’ll note that the target for each is the item clicked upon, except when I clicked outside of any component, in which case the target was null. The currentTarget is the application (Ch04_01) and the phase is 3, bubble, for every click. This is because the only event handler was assigned to the application itself. Let’s see what happens when the components get their own event handlers.
<s:VGroup id="myVGroup" paddingLeft="10" paddingTop="10" click="reportOnEvent(event);"> <s:Label id="myLabel" text="Click on Me!" click="reportOnEvent(event);" /> <s:Panel title="Results"> <s:RichText id="results" click="reportOnEvent(event);" /> </s:Panel> </s:VGroup>
Each component now also calls the reportOnEvent() function when a click event occurs.
The figure shows the results after clicking upon the components in the same order as in Step 6: VGroup, Label, RichText, nothing. Now when you click on a component, the first event trigged has matching target and currentTarget values, and occur in the second phase (target). Secondarily, after each target phase, one or more bubble phase events are triggered, depending upon how nested the target is. For example, clicking on the VGroup creates one target phase event (when the VGroup’s event handler is triggered) and one bubble phase event (when the Application’s event handler is triggered). In this latter event, the target remains the VGroup but the currentTarget becomes the application (Ch04_01).
You may also notice that no capture phase events are taking place (event phase 1). This is because capture phase event handling is disabled by default. Later in the chapter I’ll show you how to change that.
Using Specific Events
As mentioned earlier, it’s often best to use specific event object types in your functions rather than the generic Event. Doing so requires no change in how the function call is defined:
<s:Button text="Click Here!" click="myEventHandler(event);" />
But you do need to change the expected parameter type in the handling function:
private function myEventHandler(event:EventType):void { // Actually functionality. }
The EventType value needs to be one of the defined types in ActionScript: MouseEvent, KeyboardEvent, DateChooserEvent, ToolTipEvent, etc. Here’s how the moveMe() function would be written to take a MouseEvent object:
private function moveMe(event:MouseEvent):void { event.target.x += 10; }
By specifying the event type, you can take advantage of that event’s extended abilities. For example, MouseEvent has stageX and stageY properties that reflect where, on the application’s stage, the mouse was clicked. You could use that to move an image to the user-designated location:
private function moveImage(event:MouseEvent):void { myImage.x = event.stageX; myImage.y = event.stageY; }
With this particular event handler, it would have to be associated with the application, or a container, and you’d have to reference the image directly by its id, as it wouldn’t be the target of the event (because you wouldn’t be clicking on the image).
Before getting any further, understand that in order for the application to have access to that event type definition, you may need to import the corresponding class or package. Many events, like MouseEvent and KeyboardEvent are part of the flash.events package, which does not need to be manually imported. Some other events, like ToolTipEvent and DropDownEvent are defined within mx.events and spark.events respectively. If you want to use one of these other event types in a function, you’ll need to import the class first:
import spark.events.*; import mx.events.*;
The ActionScript documentation shows the package each class is defined in.
Using specific types of event objects in your code will:
- Provide additional functionality through added properties and methods
- Result in tighter, less bug-prone code
- Perform better
- You’ll see examples of this in action over the course of the rest of the chapter.