User Guide
94 Chapter 3: Using Best Practices
Using listener syntax
There are several ways to write listeners for events in Flash MX 2004. Some popular techniques
are shown in the following code examples. The first example shows a properly formatted listener
syntax, which uses a Loader component to load content into a SWF file. The
progress event
starts when content loads, and the
complete event indicates when loading finishes.
var box_ldr:mx.controls.Loader;
var ldrListener:Object = new Object();
ldrListener.progress = function(evt:Object) {
trace("loader loading:"+Math.round(evt.target.percentLoaded)+"%");
};
ldrListener.complete = function(evt:Object) {
trace("loader complete:"+evt.target._name);
};
box_ldr.addEventListener("progress", ldrListener);
box_ldr.addEventListener("complete", ldrListener);
box_ldr.load("http://www.macromedia.com/images/shared/product_boxes/159x120/15
9x120_box_flashpro.jpg");
The following example shows another recommended way of using a listener. In this example, you
define a function that is called when the user presses a Button component instance on the Stage:
var submit_button:mx.controls.Button;
submit_button.clickHandler = function(evt:Object) {
trace(evt.target._name);
}
By appending Handler to the event name (in this case, click), the event is caught, and you trace
an instance name when a user clicks the button.
A slight variation on the first example in this section is to use the
handleEvent method, but this
technique is slightly more cumbersome. It is not recommended, because you must use a series of
if..else statements or a switch statement to detect what event is caught.
var box_ldr:mx.controls.Loader;
var ldrListener:Object = new Object();
ldrListener.handleEvent = function(evt:Object) {
switch (evt.type) {
case 'progress' :
trace("loader loading:"+Math.round(evt.target.percentLoaded)+"%");
break;
case 'complete' :
trace("loader complete:"+evt.target._name);
break;
}
};
box_ldr.addEventListener("progress", ldrListener);
box_ldr.addEventListener("complete", ldrListener);
box_ldr.load("http://www.macromedia.com/images/shared/product_boxes/159x120/15
9x120_box_flashpro.jpg");