Accessibility

Community Publishing

Created:
2009-09-11
User Level:
Beginner
Products:
Flash Builder all
Flex all


Basics of event handling with ActionScript 3.0 and Flex components

 With Flex components, the code you write to handle events is a little different than in pure ActionScript 3.0. It's worthwhile to take a few minutes to first understand the AS3 underpinnings. In AS3, the standard code for handling events is as follows:

function eventResponse(eventObject:EventType):void 
{ 
    // Actions performed in response to the event go here. 
}

eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse); 
		

As explained in the Programming ActionScript 3.0 topic on event handling:

This code does two things. First, it defines a function, which specifies the actions that will be performed in response to the event. Next, it calls the addEventListener() method of the source object, in essence “subscribing” the function to the specified event so that when the event happens, the function’s actions are carried out. When the event actually happens, the event target checks its list of all the functions and methods that are registered as event listeners. It then calls each one in turn, passing the event object as a parameter.

Let's illustrate this explanation with a common event: clicking a button to submit a form. First, I need to verify what events are supported for my event target, the button. I check the Button class documentation in the ActionScript 3.0 Reference and find a list of events that Button supports. Button has a click event, which is what I want. By reading about the click event, I find that the event type is MouseEvent. So I'm able to fill in most of the event handling formula now:

function submitForm(event:MouseEvent):void {
    // Actions performed in response to the event go here.
}

myButton.addEventListener(MouseEvent.CLICK, submitForm)

The function name I used is submitForm(), but it can be named anything that reflects the actions performed. Note that "event" is commonly used for the event object parameter name, but you can name that anything you want as well. 

That's the AS3 code. With a Flex component, you define the event handling function in ActionScript as usual. But instead of explicitly calling the addEventListener() function in your ActionScript code, simply set the component's event attribute in MXML, passing the name of your event handling function:

<s:Button click="submitForm(event)"/>

Read a thorough, detailed description of event handling in ActionScript 3.0.

See more basic Flex event handling examples. These show event handling in context of an MXML file.

 

 

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License