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

Home > Articles > Web Design & Development

Effortless Flex 4 Development: Fundamental Concepts of Event Management

In order for applications to be truly a user experience (which is to say, interactive), you need to know how to manage events. Larry Ullman shows you how event management works in Flex 4.
From the book

If you’ve been reading this book sequentially, you should already have a pretty sound sense of the Flex landscape. The first chapter shows how to create applications. The second introduces the basic elements of a user interface. And the third teaches the fundamentals of ActionScript programming. But in order for applications to be truly a user experience (which is to say, interactive), you need to know how to manage events. A lot of what applications do is watch for, and respond to, events.

You can develop Flash content using Flash Professional, the old standard, or Flash Builder (nee, Flex Builder). The primary approach with Flash Professional is movie-like: action takes place over time. Conversely, Flex development is event-driven: the application is told to respond to things that happen. This take may be different than what you’ve done before, but it’s really easy to adopt. If anything, the biggest hurdle will be making the most of what’s possible.

Flex uses an event system that’s quite close to the Document Object Model (DOM) Level 3 Event Specification present in Web browsers (to varying degrees). What this means is that if you’d done a wee bit of JavaScript programming, much of the syntax and theory in this book will be familiar. And even if you haven’t, you may be pleasantly surprised to see how obvious much of this information is. For example, can you guess what event represents the cursor going over an element? Yes, mouseOver.

The chapter begins with several pages discussing the premise of event management and what pieces are involved. Then you’ll learn how to handle events by placing ActionScript code within MXML components. The third section of the chapter walks through using functions to handle events (the functions are called event handlers in such circumstances). After that, I discuss the types of events in a bit more detail. The chapter concludes with an alternate way to manage events in an application.

Fundamental Concepts

Event-driven development can be summed up as: when this event occurs with this thing take these actions. Just a few examples of are:

  • Fetch some data from a server after the application loads.
  • Change the choices in one dropdown menu after the user makes a selection in another (e.g., one dropdown represents car makes, the other car models).
  • Reveal a block of information when the user moves the cursor over an image.
  • Make new application options available once a network connection is detected.
  • Store user-supplied data in a database after the user clicks a button.
  • Move some other components around after one is removed.
  • Update the contents of a datagrid (a table-like component) as new information becomes available.

The events are already predefined for you within the framework. Events fall under two categories: system events and user events. System events are user-agnostic. Specific types include the application being fully loaded (i.e., ready to run), components being created, responses being received (like from a network connection), and so forth. User events are the direct result of a user action: moving the cursor, typing in a text input, selecting from a dropdown menu, checking a checkbox, clicking a button, and more.

The things involved are the application’s elements: its controls, containers, even the root application itself. The actions to be taken are defined by you, and represent the greatest range of possible options. This is where you would decide to update a dropdown menu, show a block of information, and so forth.

Once you’ve identified the event you want to watch for and the element it should be associated with, there are two ways of telling the application what actions to take when that event occurs. You can place your instructions inline or in a function. Chapter 3, “The ActionScript You Need to Know,” demonstrated both. This button gets moved over ten pixels every time it is clicked:

<s:Button id="myButton" x="20" y="20" click="myButton.x += 10" label="Click Me!" />

The inline ActionScript, used as the value for the click property, does the work.

Chapter 3 also had examples of the click event calling a user-defined function:

<fx:Script><![CDATA[
private function moveMe():void {
	myButton.x += 10;
}
]]></fx:Script>
<s:Button id="myButton" x="20" y="20" click="moveMe();" label="Click Me!" />

Again, this is all there really is to event-driven programming: tell the application that when this event occurs with this thing take these actions. Establishing this connection in your application results in event handlers, also called event listeners.

Before moving on, there are two more things to understand about events in Flash and Flex. First, the events themselves are going to occur whether you address them or not. Say you have a VGroup that has not been instructed to respond to a mouseover event:

<s:VGroup>
</s:VGroup>

When the user moves the cursor over this VGroup, the mouseover event still occurs, but nothing happens as a response.

It’s also important to know that Flex events are asynchronous, which means that they don’t have to wait for each other, or their responses. In other words, multiple events and multiple event reactions can, and often will, take place simultaneously. For example, while a user may be moving the cursor over a component, the application itself may also be handling the data sent back from a server request.

The Event Object

ActionScript is an object-oriented language, which means that most everything you work with in Flex, from components to strings, is an object. This includes events, as well. ActionScript has a generic Event class that defines much of the functionality needed to work with events. From this root class, there are many children that inherit from Event; each child being a more specific type of event. Every time an event occurs within a Flash application, some type of object from the Event lineage is created.

The Event family of objects, like any other, has properties and methods for you to use. Here are the three key properties:

  • type
  • target
  • currentTarget

The Event’s type property reflects what kind of event just happened. This may be click, initialize, mouseover, change, etc. The actual values will be represented by constants like MouseEvent.CLICK.

The target property of Event is an object reference to the component that generated the event. If you click on a CheckBox with an id of someCheckBox, the target of that click event will be someCheckBox. This means that by referencing the Event’s target property, you can get to the properties and methods of that target object. This will mean more later in the chapter.

The currentTarget property, as well as two others—bubbles and eventPhase—comes into play when dealing with the flow of events, to be covered next.

More specific event types add new properties and methods. For example, the MouseEvent object has an altKey property that returns a Boolean value indicating if the ALT key was pressed when the mouse event took place. When you go to handle events, you have the option of working with the generic Event object or a specific event object. You’ll see this later in the chapter.

You’ll want to familiarize yourself with the ActionScript documentation for the various events. Start by looking up the flash.events.Event class in either the standalone Adobe Help application or online (http://help.adobe.com/en_US/FlashPlatform//reference/actionscript/3/flash/events/Event.html, Figure 4.1). Near the top of the page are links you can click to go directly to listings of the class’s properties, methods, and constants. The top of the page also shows every class that is derived from Event (i.e., subclasses). You can click on any subclass name to see the documentation for that class.

The second thing you’ll often want to do within the ActionScript documentation is view the events that can be triggered by any given component. If you load the reference for a component, like Label in Figure 4.2, you’ll see an Events link near the top of the page after Properties and Methods. Clicking on that link takes you to the full listing of events that the component supports. There are several dozen possible events just for the Label component, and all that component does is display a bit of text!

Obviously, considering the limitations of a book, I cannot go through uses of every possible event for every possible component (and you wouldn’t want that anyway), which is why you’ll need to familiarize yourself with navigating the ActionScript documentation. If you’re using Flash Builder, you’ll see that it provides code hinting for common and available events, too. Events in Flash Builder are represented by a lightning bolt (Figure 4.3).

Later in the book I’ll cover movement-related events (for dragging and dropping), and those having to do with effects. There are also many events specific to AIR application development. These include AIREvent, FileEvent, SQLEvent, among others. Any property, constant, or method only available in AIR applications are marked with the AIR icon (as in the Label’s contextMenu event in Figure 4.4).

Event Flow

The final thing to know about events, before getting into some actual programming, is how events are propagated in an application, which is to say how events move about. It’s not as simple as just clicking a Button creates a click event: that does happen, but so does much more.

To start, let’s say there’s a Label within a Panel that’s a direct child of the Application:

<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" minWidth="955">	
	<s:Panel>
		<s:Label id="myLabel" text="Click on Me!" click="doThis();"/>
	</s:Panel>
</s:Application>

When the user clicks on the Label, they’ve also clicked on the Panel and on the Application. The program then needs to figure out how that event should be handled. To do so, the event goes through three phases looking for event handler assignments (Figure 4.5):

  1. Capture
  2. Target
  3. Bubble

In the capture phase the program will start looking for event handlers from the outside (or top) parent to the innermost one. The capture phase stops at the parent of the object that triggered the event. So in my example, the capture phase starts at the Application and ends at the Panel. If either component has an associated event handler, it will be triggered during this phase (and, consequently, before the Label’s event handler).

By default, the capture phase is disabled as it’s not commonly used and it can take its toll on the application’s performance. But you can define event handlers to watch the capture phase when needed. You might do so to handle an event in a parent component, then prevent it from being handled within a child. Towards the end of the chapter I’ll discuss this less common approach to event management.

The second phase, target, is the most important phase. Here the actual subject of the event (i.e., the component that triggered it) is checked for an event handler. This is where most event handling takes place.

Finally, the bubble phase is like capture in reverse, working back through the structure, from the target component’s parent on up. There are a couple of reasons you may add handlers to parent components that will catch events during the bubble phase:

  • To execute additional actions, besides those triggered by the target phase.
  • To execute the same actions when an event is triggered by any of a component’s children.

For example, if you have a form with multiple components, you may want to validate an individual component when that component’s value changes, and also do something with the entire body of form data at the same time.

The event object’s eventPhase property stores a number, also represented by a constant, that reflects the current stage (Table 4.1).

Table 4.1: Event Phase Values and Constants

Value

Constant

1

EventPhase.CAPTURING_PHASE

2

EventPhase.AT_TARGET

3

EventPhase.BUBBLING_PHASE

Do note that just as not every component can trigger every event type, not all events participate in all three phases. The event object’s bubbles property returns a Boolean indicating if the event participates in the bubbling phase, in particular.

As already mentioned, the event object’s target property refers to the component that triggered the event. This value will not change over the course of the event flow. In the example I’m discussing, the target would always be the Label object (assuming that was what the user clicked).

The event object also has a currentTarget property that reflects the object currently being examined for an event handler. This value will change repeatedly over the course of the event flow. In the Label-Panel-Application example, the currentTarget would go from Application to Panel (in the capture phase) to Label (in target) to Panel to Application (in the bubble phase). I’ll demonstrate a utility program in this chapter that may help you understand the phases and targets.

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.

Overview


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.

Surveys

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.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

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.

Security


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

Children


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

Marketing


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 customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


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: www.peachpit.com/u.aspx.

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 NevadaDesignatedRequest@pearson.com.

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.

Links


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