
Beginning ActionScript 2.0 2006
.pdf
Chapter 10
2.A method with the same name as the name of the event is assigned to the object:
var imageListListener:Object = new Object(); imageListListener.change = function(eventObject:Object)
{
// Handler code goes here
}
3.The listener is registered to a component:
var imageListListener:Object = new Object(); imageListListener.change = function(eventObject:Object)
{
// Handler code goes here
}
imageList.addEventListener(“change”, imageListListener);
Every time the imageList component generates a change event from the user’s selecting a different value, the listener code runs. To handle multiple events from the same component, you add additional methods to the event listener object, and then make additional calls to addEventListener():
var imageListListener:Object = new Object(); imageListListener.change = function(eventObject:Object)
{
// Handler code goes here
}
imageListListener.itemRollOver = function(eventObject:Object)
{
// Handler code goes here
}
imageListListener.itemRollOout = function(eventObject:Object)
{
// Handler code goes here
}
imageList.addEventListener(“change”, imageListListener); imageList.addEventListener(“itemRollOver”, imageListListener);
imageList.addEventListener(“itemRollOut”, imageListListener);
Every time an event listener is called, it is passed a handle to an event object. The event object contains two properties:
type — Gives the name of the event that was generated.
target — Holds a reference to the component that generated the event.
The target property is indispensable because it provides the information that you need about the state of the calling component. The following code shows how you use the target property to access the value (the visible label) and the data property for the row that the user clicked:
var imageListListener:Object = new Object(); imageListListener.change = function(eventObject:Object)
{
trace(eventObject.target.selectedItem.value);
trace(eventObject.target.selectedItem.data);
}
imageList.addEventListener(“change”, imageListListener);
248

Interacting with the User
The code gets a handle to the target (a List component) from the event object. From that handle, any List component properties or methods can be used. The List component property used here is selectedItem, which holds a reference to the last selected row. Each row is a custom object that consists of two properties:
value — Holds the label that is shown to the user.
data — Holds a non-viewable piece of data associated with the selected row.
Different components provide different ways of getting to the information about the event from within the handler. The List component is a common way of doing it. The Menu component is different. Instead of exposing a target property, it exposes a menuBar, a menu, and a menuItem property. The menuItem property is generally the one to use because it holds the data used to generate that menu item. The following example shows how the label for the selected menu item can be retrieved:
var menuListener:Object = new Object(); menuListener.change = function (eventObject:Object)
{
trace(“Selected menu item: “ + eventObject.menuItem.attributes.label);
}
It isn’t possible to remember all of the ways to access event data for each component, but there is an easy way to get to that information. Open in turn the built-in Help panel (F1), the Components Language Reference section, and the subsection for the component with which you’re working. In the documentation for the component is a page called “<Component Name> Class” that outlines each of the applicable properties, methods, and events. Look for the name of the event that you want to work with, and then look for the page with the same name in that section. It provides the details on how to access the event data for the component.
Try It Out |
Creating a Listener Object |
In this exercise you create an event listener. Just follow these steps:
1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.
2.Rename the existing layer in the timeline to Script. Create a new layer, Components, below the Script layer.
3.Click the keyframe on the Components layer to select it. Open the Components panel (Window Components) and then open its User Interface section. Drag one Button component to the stage.
4.Open the Properties panel (Window Properties), click the button on the stage, and set the instance ID in the text field at the top left of the panel to myButton.
5.The code for this example is very small, so enter it in the Actions panel instead of creating a separate .as file. Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:
var buttonListener:Object = new Object(); buttonListener.click = function(eventObject:Object)
{
249

Chapter 10
trace(“Button clicked”);
}
myButton.addEventListener(“click”, buttonListener);
6.Select File Save As, name the file tryItOut_listenerObject_1.fla, choose an appropriate directory, and save it. Select Control Test Movie.
How It Works
This example shows how to use an event listener object to capture an event. The listener object is created, a custom method with the same name as the event to be captured is created, and the listener object is registered with the component.
The previous example showed only a simple situation. Now you’re ready for something a bit more complex.
Try It Out |
A More Involved Listener Object Setup |
This exercise expands on how to work with event listener objects. Figure 10-1 shows the result.
Figure 10-1
1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.
2.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:
#include “tryItOut_listenerObject_2.as”
3.Rename the existing layer in the timeline to Script. Create a new layer, Components, below it.
4.Open the Components panel (Window Components), and then open its User Interface section. Drag one Button component, three CheckBox components, and three RadioButton components to the stage. Arrange them as shown in Figure 10-1.
5.Open the Properties panel (Window Properties), click each component in turn, and set an instance ID in the text field at the top left of the panel. Name the checkboxes dinnerOption1, dinnerOption2, and dinnerOption3. Name the radio buttons dessertOption1, dessertOption2, and dessertOption3. Name the button orderButton.
250

Interacting with the User
6.Select the Parameters tab in the Properties panel. Click the checkboxes to set their label components: Curried Lamb, Samosa, and Garden Salad.
7.Click the radio button components and set the following values:
Data |
Label |
Group Name |
chocolateMousse |
Chocolate Mousse |
dessertOptions |
applePie |
Apple Pie |
dessertOptions |
tiramisu |
Tiramisu |
dessertOptions |
8.Select File Save As, name the file tryItOut_listenerObject_2.fla, choose an appropriate directory, and save it.
9.Create a new Macromedia Flash document, name it tryItOut_listenerObject_2.as, and save it in the directory containing the Flash project file.
10.Enter the following code in the new ActionScript file:
//Handle the selection of one of the dinner checkboxes
var dinnerOptionListener:Object = new Object(); dinnerOptionListener.click = function(eventObject:Object)
{
var checkBoxLabel:String = eventObject.target.label;
var isCheckBoxSelected:Boolean = eventObject.target.selected; if (isCheckBoxSelected == true)
{
trace(“Selected: “ + checkBoxLabel);
}
else
{
trace(“Deselected: “ + checkBoxLabel);
}
}
dinnerOption0.addEventListener(“click”, dinnerOptionListener); dinnerOption1.addEventListener(“click”, dinnerOptionListener); dinnerOption2.addEventListener(“click”, dinnerOptionListener);
//Handle the selection of one of the dessert radio buttons var dessertOptionListener:Object = new Object(); dessertOptionListener.click = function(eventObject:Object)
{
var radioButtonLabel:String = eventObject.target.selection.data; trace(“Selected: “ + radioButtonLabel);
}
dessertOptions.addEventListener(“click”, dessertOptionListener);
//Handle the clicking of the order button
var parentTimeline:MovieClip = this;
var orderButtonListener:Object = new Object(); orderButtonListener.click = function(eventObject:Object)
{
251

Chapter 10
var myOrder:String = “Ordering: “;
var tempCheckBoxHandle:mx.controls.CheckBox;
//Find out which dinner options were checked for (var i:Number = 0; i < 3; i++)
{
tempCheckBoxHandle = parentTimeline[“dinnerOption” + i]; if (tempCheckBoxHandle.selected == true)
{
myOrder += tempCheckBoxHandle.label + “, “;
}
}
//Find out which dessert was selected
if (dessertOptions.selection != undefined)
{
myOrder += dessertOptions.selection.label;
}
trace(myOrder);
}
orderButton.addEventListener(“click”, orderButtonListener);
11.Save the file, return to the Macromedia Flash project file, and select Control Test Movie.
How It Works
Three sets of components each generate a click event, so three sets of listener objects are created. The first listener handles the clicking of any of the checkboxes. First, an associative array is created to keep track of what was selected for later reference:
var dinnerOrderArray:Array = new Object();
Then the listener object is created, and a method is added to the object with the same name as the event to be captured:
var dinnerOptionListener:Object = new Object(); dinnerOptionListener.click = function(eventObject:Object)
{
// ...
}
A handle to the component that generated the event is obtained from the event object. With this, you can find out the text label for the component, as well as whether it was checked:
var checkBoxLabel:String = eventObject.target.label;
var isCheckBoxSelected:Boolean = eventObject.target.selected; if (isCheckBoxSelected == true)
{
trace(“Selected: “ + checkBoxLabel);
}
else
{
trace(“Deselected: “ + checkBoxLabel);
}
252

Interacting with the User
The event listener object is then assigned to each of the checkboxes:
dinnerOption1.addEventListener(“click”, dinnerOptionListener); dinnerOption2.addEventListener(“click”, dinnerOptionListener); dinnerOption3.addEventListener(“click”, dinnerOptionListener);
The same process is performed for the radio buttons:
// Handle the selection of one of the dessert radio buttons var dessertOptionListener:Object = new Object(); dessertOptionListener.click = function(eventObject:Object)
{
var radioButtonLabel:String = eventObject.target.selection.data; trace(“Selected: “ + radioButtonLabel);
}
dessertOptions.addEventListener(“click”, dessertOptionListener);
The process for adding listener objects to radio buttons is a bit different, in that radio buttons actually have a parent component called RadioButtonGroup that tracks the last selected radio button. Setting the groupName parameter on the Parameters tab automatically creates the group and associates the radio button with that group. As a result, the event listener needs to be assigned only once to the radio button group instead of three times to each radio button.
A reference to the timeline is kept for use in the button handler code, where this refers to the base timeline, _level0:
var parentTimeline:MovieClip = this;
Next, the listener for the order button is created:
// Handle the clicking of the order button var orderButtonListener:Object = new Object();
orderButtonListener.click = function(eventObject:Object)
{
// ...
}
orderButton.addEventListener(“click”, orderButtonListener);
The code loops through all the checkboxes, looking for ones that are checked. When it finds one, the label of the selected checkbox is added to an output string that lists everything that has been ordered:
var myOrder:String = “Ordering: “;
var tempCheckBoxHandle:mx.controls.CheckBox;
// Find out which dinner options were checked for (var i:Number = 0; i < 3; i++)
{
tempCheckBoxHandle = parentTimeline[“dinnerOption” + i]; if (tempCheckBoxHandle.selected == true)
{
myOrder += tempCheckBoxHandle.label + “, “;
}
}
253

Chapter 10
The associative array syntax in the loop is used to get the selected state and label of each checkbox. You can do this without the loop:
var myOrder:String = “Ordering: “;
// Find out which dinner options were checked if (dinnerOption0.selected == true)
{
myOrder += dinnerOption0.label + “, “;
}
if (dinnerOption1.selected == true)
{
myOrder += dinnerOption1.label + “, “;
}
if (dinnerOption2.selected == true)
{
myOrder += dinnerOption2.label + “, “;
}
But, obviously, this would get quite unwieldy with any more than a few checkboxes.
The radio button group is checked, and the label for the selected radio button is added to the order list:
// Find out which dessert was selected
if (dessertOptions.selection != undefined)
{
myOrder += dessertOptions.selection.label;
}
Finally, the order is made:
trace(myOrder);
Variation of Creating a Listener Object
A variation of the technique just discussed is a little cleaner for some applications. The general idea is that instead of creating a new listener object to hold the event handlers, you use an existing object such as the main timeline:
change = function(eventObject:Object)
{
// Handler code goes here
}
imageList.addEventListener(“change”, this);
This is sometimes convenient for simple cases with only one listener object. Because it can support only one listener object, though, its usage is discouraged in favor of the original listener object technique.
254

Interacting with the User
Try It Out |
Using the Stage as a Listener |
In this exercise you use the stage to hold an event listener.
1.Create a new Macromedia Flash document.
2.Rename the existing layer in the timeline to Script. Create a new layer below it called
Components.
3.Click the keyframe on the Components layer to select it. Open the Components panel (Window Components) and then open its User Interface section. Drag one Button component to the stage.
4.Open the Properties panel (Window Properties), click the button on the stage, and set the instance ID in the text field at the top left of the panel to myButton.
5.The code for this example is small, so enter it in the Actions panel instead of creating a separate ActionScript file. Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:
click = function(eventObject:Object)
{
trace(“Button clicked”);
}
myButton.addEventListener(“click”, this);
6.Select File Save As, name the file tryItOut_stageListener.fla, choose an appropriate directory, and save it. Select Control Test Movie.
How It Works
This example shows how you would use the timeline as an event listener object. The timeline is a child of the Object class, making it a candidate to hold custom methods.
Creating a Listener Function
Another variation of the listener involves using a regular function instead of an object:
function myChangeHandler(eventObject:Object)
{
// Handler code goes here
}
imageList.addEventListener(“change”, myChangeHandler);
This is more in line with how events are handled outside components, where functions are assigned to a property representing the event. One of the differences between a listener function and a listener object is that of variable scope. Consider what happens when using the this keyword in a listener object and a listener function. First, the listener object:
imageListListener.change = function(eventObject:Object)
{
trace(this);
255

Chapter 10
}
imageList.addEventListener(“change”, this); // Outputs: [object Object]
Next, the listener function:
function myChangeHandler(eventObject:Object)
{
trace(this);
}
imageList.addEventListener(“change”, myChangeHandler); // Outputs: _level0.imageList
Recall that this refers to the containing object for any code that calls it. When called from code placed directly on the main timeline, it refers to the timeline. When called from a class or a function called by a class, it refers to the class instance. In the case of the listener object, this refers to the listener object itself. In the case of the listener function, this refers to the calling component. As a result of this listener function characteristic, you can access all of the component’s properties and methods without having to access the event object. The following code shows that the List component properties rowCount and selectedItem can be directly accessed from within the listener function:
function myChangeHandler(eventObject:Object):Void
{
trace(“num rows: “ + this.rowCount); trace(“row data: “ + this.selectedItem.data);
}
imageList.addEventListener(“change”, myChangeHandler);
//Outputs:
//num rows: 4
//row data: http://www.nathanderksen.com/book/fullsize/aStudyInTexture.jpg
As a result, the handle to the event object is not needed in this case.
Try It Out |
Using a Listener Function |
In this exercise you learn how to use a listener function. Just follow these steps:
1.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.
2.Rename the existing layer in the timeline to Script. Create a new layer below the script layer called Components.
3.Click the keyframe on the Components layer to select it. Open the User Interface section of the Components panel. Drag two Button components to the stage.
4.Open the Properties panel (Window Properties), select the first button on the stage, and set the instance ID in the text field at the top left of the panel to playButton. Select the second button on the stage and set the instance ID to pauseButton.
5.The code for this example is small, so enter it in the Actions panel instead of creating a separate ActionScript file. Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and type in the following ActionScript code:
256

Interacting with the User
function buttonHandler(eventObject:Object):Void
{
switch(this._name)
{
case “playButton”: trace(“Pressed play button”); break;
case “pauseButton”: trace(“Pressed pause button”); break;
}}
playButton.addEventListener(“click”, buttonHandler); pauseButton.addEventListener(“click”, buttonHandler);
6.Name the file tryItOut_listenerFunction.fla, and save it in an appropriate directory. Select Control Test Movie.
How It Works
In this example you created a single listener function that handles events from multiple Button components. The function has access to the name of the button, which it uses to decide how to respond.
Which Listener Technique Should You Use?
Basically, you should use the listener technique with which you’re most comfortable. The listener object technique is the one in most widespread use, and almost all documentation shows it within the examples. The code for the variation that uses the stage as a listener object looks a bit cleaner and is fine for very simple projects, but it loses the versatility that the listener is supposed to provide. The listener function technique is very rarely seen in the wild, possibly because few people know about it; however, its structural similarity to older event-handling techniques makes it a bit easier to understand and work with, while its broadcast qualities give the same advantages that listener objects provide.
Try It Out |
Adding Event Handlers to Your Image Viewer |
In this exercise you add listener event handlers to the picture viewer to respond to user interactions. You also put into place the remaining code needed to make this a functional example. Here are the steps to follow:
1.Open the completed tryItOut_scriptingComponents.fla file from the preceding Try It Out exercise, or open tryItOut_scriptingComponents.fla from the book’s source files at <source file directory>/Chapter 10/tryItOut_scriptingComponents_v2/.
2.Open the completed tryItOut_scriptingComponents.as file from the preceding Try It Out exercise, or open tryItOut_scriptingComponents.as from the book’s source files at <source file directory>/Chapter 10/tryItOut_scriptingComponents_v2/.
3.Copy the <source file directory>/Chapter 10/tryItOut_scriptingComponents_v2/images directory (not just the directory contents) into the directory containing your .fla and .as files.
257