Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
831,44 KB
Nội dung
Chapter 7: Working with Events
221
As shown in Figure 7.8, the Variables view displays the event object’s type and all its current prop-
erty values.
FIGURE 7.8
The event object’s type displayed in the Variables view
Reading the documentation
Documentation for every event in the Flex SDK includes the type of the event object that will be
dispatched when the event occurs. For example, the documentation for the
Button class’s click
event shows that the event object is an instance of
flash.events.MouseEvent. To find this
information, follow these steps:
1. Place the cursor in the object declaration in Source view.
2. Press F1 to display a list of Help subjects.
3. Click the link for the class or component you’re using.
4. In the API documentation, click the Events link.
5. Locate the event you’re interested in, and click its link.
As shown in Figure 7.9, you should see the specific type of the class that will be dispatched for that
event.
Handling specific event objects
To capture information that’s available only in one of the extended event classes, declare the
datatype of an event handler function’s
event argument as that class. For example, this event han-
dler function expects an instance of
MouseEvent:
12_488959-ch07.indd 22112_488959-ch07.indd 221 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Part I: Flex Fundamentals
222
private function clickHandler(event:MouseEvent):void
{
myLabel.text=”You clicked; was the alt key pressed? “ +
event.altKey;
}
FIGURE 7.9
Documentation for the click event
The altKey property is available only because the event argument is declared as the subclass
that supports that property. If the
event argument instead is declared as the Event superclass,
the
altKey property isn’t recognized by the compiler, and a compiler error results.
The complete application shown in Listing 7.4 is an application that captures a
MouseEvent and
displays the status of the keys on the keyboard at the moment the event is dispatched.
LISTING 7.4
An application that handles a MouseEvent object
<?xml version=”1.0” encoding=”utf-8”?>
<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”>
<s:layout>
<s:VerticalLayout horizontalAlign=”center” paddingTop=”20”/>
</s:layout>
<fx:Script>
12_488959-ch07.indd 22212_488959-ch07.indd 222 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7: Working with Events
223
<![CDATA[
private function clickHandler(event:MouseEvent):void
{
myText.text=”The “ + event.type +
“ event was dispatched by “ + event.target.id;
altText.text=”Alt key pressed: “ + event.altKey;
ctrlText.text=”Ctrl key pressed: “ + event.ctrlKey;
shiftText.text=”Shift key pressed: “ + event.shiftKey;
}
]]>
</fx:Script>
<s:Label id=”myText”/>
<s:Label id=”altText”/>
<s:Label id=”ctrlText”/>
<s:Label id=”shiftText”/>
<s:Button id=”myButton” label=”Click Me” click=”clickHandler(event)”/>
</s:Application>
On the Web
The code in Listing 7.4 is available in the Web site files in the chapter07 project as MouseEventObject
Properties.mxml
.
n
Handling Events with addEventListener()
You also can set up event handlers with a method named addEventListener(). This method
is defined in an ActionScript class named
EventDispatcher, which appears in the inheritance
hierarchy of every ActionScript class that’s able to dispatch events. Stated more briefly, you can call
addEventListener() from any object that knows how to dispatch an event.
Setting up an event listener
The following MXML code declares a Button component with a click event handler:
<s:Button id=”myButton” label=”Click Me”
click=”clickHandler(event)”/>
The following code uses the addEventListener() method instead of the MXML-based event
handler to accomplish the same task:
myButton.addEventListener(“click”, clickHandler);
The first argument you pass to addEventListener() is the name of the event you’re listening
for. The second argument is the name of the function you want to call when the event is
dispatched.
12_488959-ch07.indd 22312_488959-ch07.indd 223 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Part I: Flex Fundamentals
224
Caution
Notice that you pass the name of the function as the second argument, not the complete code required to call
the function. You’re designating which function to call, rather than calling the function immediately.
n
The object from which you call addEventListener() always calls the listener function with
the same signature, passing a single argument that’s datatyped as the appropriate event class for
that event. Event listener functions designed to be used with
addEventListener() always have
the same signature:
[access modifier] function [functionName](
event:[event class data type]):void
{}
So a function designed to receive an instance of MouseEvent always looks like this:
private function clickHandler(event:MouseEvent):void
{
execute event handling code
}
Tip
The event handler function’s access modifier doesn’t necessarily have to be private. But if the function is
only used within the current component, there’s no need to further broaden access to the function.
n
You typically call addEventListener() during application startup or initial object construc-
tion, where it can replace an MXML-based event handler definition. For example, you might set up
your event listeners in a function named
app_creationCompleteHandler() that’s called
The fact that you can define an event handler function to expect either the specific event class, such as
MouseEvent, or its superclass, such as Event, is a reflection of the support for polymorphism in
ActionScript’s implementation of object-oriented programming. I describe the concept of polymor-
phism in detail in Chapter 1. Merriam-Webster defines polymorphism as “the quality or state of existing
in or assuming different forms.” In this case, the different forms the event object takes are its native type
(
MouseEvent) or its superclass type (Event).
One reason some developers set an event object to the superclass is because they don’t know the
event’s native class type and don’t want to take time to look it up. This sounds lazy, but in many cases
the specific properties of the native type just aren’t needed in that situation, and using the
Event super-
class makes for faster programming.
You also can use the superclass type to make a function reusable with events that dispatch different
native types, again where they don’t need the specific properties that are supported by the native types.
This is the true purpose of implementing polymorphism in object-oriented languages: to support code
that’s reusable in many different circumstances.
Event Class Inheritance and Polymorphism
12_488959-ch07.indd 22412_488959-ch07.indd 224 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7: Working with Events
225
upon the Application component’s creationComplete event. The application in Listing 7.5
uses this strategy. Notice the following:
l
The clickHandler() function returns void.
l
The app_creationCompleteHandler() function is called during application startup
upon the application’s
creationComplete event.
l
The MXML-based declaration of the Button component doesn’t have a click event
handler; this would be redundant and in fact would result in the event handler function
being called twice.
LISTING 7.5
An application that uses addEventListener()
<?xml version=”1.0” encoding=”utf-8”?>
<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”
creationComplete=”app_creationCompleteHandler(event)”>
<s:layout>
<s:VerticalLayout horizontalAlign=”center” paddingTop=”20”/>
</s:layout>
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function app_creationCompleteHandler(event:FlexEvent):void
{
myButton.addEventListener(MouseEvent.CLICK, clickHandler);
}
protected function clickHandler(event:MouseEvent):void
{
myText.text=”The “ + event.type +
“ event was dispatched by “ + event.target.id;
}
]]>
</fx:Script>
<s:Label id=”myText”/>
<s:Button id=”myButton” label=”Click Me”/>
</s:Application>
On the Web
The code in Listing 7.5 is available in the Web site files in the chapter07 project’s src folder in the default
package as
UsingAddEventListener.mxml.
n
12_488959-ch07.indd 22512_488959-ch07.indd 225 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Part I: Flex Fundamentals
226
Using event name constants
Each event class in the Flex framework implements constants that have values equal to the names
of events for which the event class is used. For example, the
MouseEvent class has many con-
stants that reflect the names of events for which this event class is dispatched (shown with their
equivalent values):
l
CLICK = “click”
l
MOUSE_DOWN = “mouseDown”
l
MOUSE_UP = “mouseUp”
l
MOUSE_MOVE = “mouseMove”
l
RIGHT_CLICK = “rightClick”
l
MOUSE_WHEEL = “mouseWheel”
There are more, but you get the picture. You use these constants in calls to
addEventListener()
instead of phrasing the event name as a literal string. For example, instead of this code:
myButton.addEventListener(“click”, clickHandler);
you can use this:
myButton.addEventListener(MouseEvent.CLICK, clickHandler);
When you use event name constants, you reduce the risk of typing errors in your code. When you
use literal strings to indicate which event you want to listen for, it’s easy to misspell the name. For
example, this code would result in an event listener that will never be triggered, because there is
no event named
clik:
myButton.addEventListener(“clik”, clickHandler);
Because the event name is phrased as a literal string, the compiler has no way of knowing that it’s
misspelled. Of course, you can make the same mistake with an event name constant:
myButton.addEventListener(MouseEvent.CLIK, clickHandler);
But in this case, the compiler would complain, telling you that there is no such property or con-
stant as
CLIK in the MouseEvent class, and you’d be able to find and fix the error at a much ear-
lier stage of development.
Another advantage of using event name constants comes from Flash Builder’s code completion
tool. As shown in Figure 7.10, when you type the name of the
MouseEvent class and add a
period, you see a list of available constants that are members of the class. You can then select the
appropriate event name and ensure that it’s typed correctly from the beginning.
Tip
When you type the id of an object that dispatches events and then a period, followed by addEventListener(,
code completion for the
addEventListener() method’s first argument displays constants for all events that
can be dispatched by the object from which
addEventListener() is being called.
n
12_488959-ch07.indd 22612_488959-ch07.indd 226 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7: Working with Events
227
FIGURE 7.10
Flash Builder’s code completion tool with event name constants
Flex Builder’s code completion with event name constants
Removing an event listener
You can remove an event listener that was set up with addEventListener() with the
removeEventListener() method. This method also is defined in the EventDispatcher
class and can be called from any object that dispatches events.
The basic syntax for
removeEventListener() is the same as addEventListener():
myButton.removeEventListener(MouseEvent.CLICK, clickHandler);
The addEventListener() and removeEventListener() methods enable you to add
and remove event listeners as needed whenever an application’s requirements change logically
at runtime.
Using Event Bubbling
Event bubbling refers to the process of dispatching events through multiple levels of inheritance.
Consider this application code, which defines a
Button control inside a VBox container:
<?xml version=”1.0” encoding=”utf-8”?>
<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”>
<s:VGroup id=”myGroup”>
<s:Button label=”Click me” id=”myButton”/>
</s:VGroup>
</s:Application>
12_488959-ch07.indd 22712_488959-ch07.indd 227 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Part I: Flex Fundamentals
228
When the Button component is clicked, it dispatches a click event. All event objects have a
Boolean property named bubbles. When this property’s value is set to true, as it is by default
with the
MouseEvent class, the event first is dispatched by the object that was clicked, then by its
container, and so on up the display tree until it’s dispatched by the application itself.
Each time the event bubbles up another containership level, the event object is received again by
the event handler for the current container. But one property is changed: Each event object has a
currentTarget property that refers to the object that’s currently dispatching the event. This
property is changed as the event object bubbles, but the event object’s
target property continues
to reference the object that originally dispatched the event.
You can stop an event from continuing to bubble through the containership hierarchy by calling a
method of the event object named
stopPropagation():
event.stopPropagation();
This is sometimes necessary when a common event such as click might otherwise be handled in
ways that don’t work for your application.
Tip
Another way to stop a visual component from dispatching mouse events is to set its mouseEnabled property
to false.
n
The application in Listing 7.6 uses a two-level containership hierarchy: a Button inside a VGroup
inside an
Application. All objects handle the click event and dispatch the event object to a
clickHandler() function, where the target and currentTarget are logged. The
TextArea control that’s used to log the events explicitly handles its own click event and stops
that event from bubbling to the container and application.
LISTING 7.6
An application that logs event bubbling
<?xml version=”1.0” encoding=”utf-8”?>
<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=”clickHandler(event)”>
<s:layout>
<s:VerticalLayout horizontalAlign=”center” paddingTop=”20”/>
</s:layout>
<fx:Script>
<![CDATA[
protected function clickHandler(event:MouseEvent):void
{
eventLog.text += “target=” + event.target.id +
“, currentTarget=” + event.currentTarget.id + “\n\n”;
}
12_488959-ch07.indd 22812_488959-ch07.indd 228 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7: Working with Events
229
]]>
</fx:Script>
<s:VGroup id=”myGroup” left=”10” top=”10” width=”50”
click=”clickHandler(event)”>
<s:Button id=”myButton” label=”Click me” click=”clickHandler(event)”
horizontalCenter=”0”/>
<s:TextArea id=”eventLog”
height=”110” width=”300”
horizontalCenter=”0”
click=”event.stopPropagation()”/>
</s:VGroup>
</s:Application>
On the Web
The code in Listing 7.6 is available in the Web site files in the chapter07 project’s src folder in the default
package as
EventBubbling.mxml.
n
As shown in Figure 7.11, each time the event is handled, the target property always points to
the
Button component, while the currentTarget changes with each new call to the event
handler function.
FIGURE 7.11
An event bubbling demonstration
Tip
Event bubbling works only if the parent container declares the event you want to handle. For example, if you
try to handle a
change event from a ComboBox in a parent VBox in MXML, an error occurs because the com-
piler says there is no
change event to listen for. To overcome this limitation, create your own custom compo-
nent based on the container you want to use, and explicitly declare the selected event as a member of the new
version of the container.
n
12_488959-ch07.indd 22912_488959-ch07.indd 229 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Part I: Flex Fundamentals
230
Using Custom Events
You use custom events to communicate information and data between application components. As
I described previously, Flex applications are built with a modular architecture, with functionality
divided between multiple components. When a component needs to share information with the
rest of the application, it does so by dispatching an event.
The following MXML component displays three choices of
Small, Medium, and Large in a
group of
RadioButton components:
<?xml version=”1.0” encoding=”utf-8”?>
<s:VGroup xmlns:fx=”http://ns.adobe.com/mxml/2009”
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”>
<fx:Declarations>
<s:RadioButtonGroup id=”sizeGroup”/>
</fx:Declarations>
<s:RadioButton value=”Small”
label=”Small” groupName=”sizeGroup”/>
<s:RadioButton value=”Medium”
label=”Medium” groupName=”sizeGroup”/>
<s:RadioButton value=”Large”
label=”Large” groupName=”sizeGroup”/>
</s:VGroup>
On the Web
The previous code is available in the Web site files in the chapter07 project as components/
SizeSelectorStart.mxml
.
n
New Feature
As with all other nonvisual components, the RadioButtonGroup control must now be declared inside an
<fx:Declarations> tag set.
n
When the user clicks a radio button to make a selection, the component can share the following
information with the rest of the application:
l
The user selected something.
l
The user selected a particular bit of data.
To share the information, you’ll need to follow these steps within the component:
1. Define a custom event that the MXML component is capable of dispatching.
2. Create an event object at runtime.
3. Populate the event object with data.
4. Dispatch the event object.
12_488959-ch07.indd 23012_488959-ch07.indd 230 3/5/10 2:24 PM3/5/10 2:24 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... l You handle events with either MXML-based event handlers or the addEvent Listener() method l Event handler functions receive a single event argument and return void l FlashBuilder4 adds the capability to generate event handler functions for all Flex components and events l You can declare and dispatch custom events from your custom components l You can create custom event classes to store and send... 244 Chapter 7: Working with Events Or, if you prefer to use addEventListener(), call this code as the application starts up: myForm.addEventListener(LoginEvent.LOGIN, loginHandler); Either way, the loginHandler() function is called and the data is delivered to the application Tip FlashBuilder4 can automatically create an event handler function for custom... function sizeSelectedHandler(event:TextEvent):void { process event data here } When the event occurs, the event handler function is executed and the data can then be appropriately handled Tip FlashBuilder4 is able to automatically generate event handler functions for custom component instances in the same manner as with the Flex SDK’s built-in components n Follow these steps to handle a custom event... interface These include the UIComponent and GraphicElement classes (and their subclasses), so you can add both components (both MX and Spark) and primitives to any Spark container Tip The GraphicElement and UIComponent classes share a set of methods and properties that represent the minimum API required for layout and display within a Flex4 application These shared methods and properties are defined in the... components are inherited from the Flex 3 SDK, and many are still used in Flex4 In some cases, such as the DataGrid and its related controls, the MX versions will eventually be replaced by Spark versions as the Flex SDK evolves In other cases, such as ViewStack and other navigation containers, the Spark component set doesn’t implement the exact equivalent functionality yet, but Flex4 adds features that make... and Working with Drag and Drop Chapter 13 Managing View States Chapter 14 Declaring Graphics with MXML and FXG Chapter 15 Skinning Spark Components Chapter 16 Managing Application Navigation Chapter 17 Working with Pop-up Windows CHAPTER Using Flex Visual Controls I n previous chapters, I’ve described various aspects of Flex application development and declared instances of controls such as Label and. .. attribute to flash. events.TextEvent: [Event(name=”sizeSelected”, type= flash. events.TextEvent”)] 3 Place the cursor inside the RadioButtonGroup component start tag 4 Type itemClick and press Enter (Windows) or Return (Mac) 5 When prompted to Generate ItemClick Handler, press Enter (Windows) or Return (Mac) again You should see that FlashBuilder generates an event handler function... method if you want to be able to re-dispatch custom event objects from an event handler method l 246 Flex applications are event-driven You handle custom events and event classes with the same architecture as pre-built classes that are included in the Flex SDK Part II Designing Flex Applications IN THIS PART Chapter 8 Using Flex Visual Controls Chapter 9 Working with Text Chapter 10 Using Layout Containers... an Object and the String type is expected by the TextEvent class’s text property n Handling custom events Event handling with custom events looks just like handling events that are predefined by classes in the Flex framework You can handle a custom event in these two ways: l With an MXML-based event attribute that executes explicit ActionScript code l With the addEventListener() method Handling a custom... Ctrl+space to trigger FlashBuilder s code completion tool n Within the event handler function, extract data as needed The complete event handler function might look like this: private function loginHandler(event:LoginEvent):void { messageLabel.text = “You logged as “ + event.username + “ with a password of “ + event.password; } Then, to call the event handler function, use an MXML-based event handler, as in: . circumstances.
Event Class Inheritance and Polymorphism
12 _48 8959-ch07.indd 2 241 2 _48 8959-ch07.indd 2 24 3/5/10 2: 24 PM3/5/10 2: 24 PM
Please purchase PDF Split-Merge. event handler function is executed and the data can then be appropri-
ately handled.
Tip
Flash Builder 4 is able to automatically generate event handler