Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

From the book Functions as Event Handlers

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 Any of the target object’s available properties and methods are then accessible using For example, here’s another way of writing the moveMe() function (for moving a component):

private function moveMe(event:Event):void { += 10;

Instead of hardcoding the component’s id value in the function, you can refer to the id value of, 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')" />

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.

  1. Create a new Flex project for the Web.
  2. In the Application tag, associate the reportOnEvent() function with any click.
  3. <s:Application xmlns:fx="" 

    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.

  4. Within a Script block, define the function.
  5. <fx:Script><![CDATA[
    private function reportOnEvent(event:Event):void {
    	results.text += "Target: " + + "\ncurrentTarget: " + + "\nPhase: " + event.eventPhase + "\n----------\n";

    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.

  6. Define the components.
  7. <s:VGroup id="myVGroup" paddingLeft="10" paddingTop="10">
    	<s:Label id="myLabel" text="Click on Me!" />
    	<s:Panel title="Results">
    		<s:RichText id="results" />

    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.

  8. Save, compile, and run the application.
  9. Click on the various components, and not on any components at all, to see the results (Figure 4.13).
  10. Figure xx-xx

    Figure 4.13

    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.

  11. Add click event handlers to the VGroup, Label, and RichText components.
  12. <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);" />

    Each component now also calls the reportOnEvent() function when a click event occurs.

  13. Save, compile, and run the application.
  14. Click on the various components, and not on any components, to see the results (Figure 4.14).
  15. 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 { += 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 package, which does not need to be manually imported. Some other events, like ToolTipEvent and DropDownEvent are defined within and respectively. If you want to use one of these other event types in a function, you’ll need to import the class first:


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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020