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

Home > Articles > Web Design & Development

Effortless Flex 4 Development: Fundamental Concepts of Event Management

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account