Flash CS3 Documentation |
|||
| Programming ActionScript 3.0 > Getting started with ActionScript > Working with objects > Events > Basic event handling | |||
The technique for specifying certain actions that should be performed in response to particular events is known as event handling. When you are writing ActionScript code to perform event handling, there are three important elements you'll want to identify:
Any time you write ActionScript code to handle events, it will include these three elements, and the code will follow this basic structure (elements in bold are placeholders you'd fill in for your specific case):
function eventResponse(eventObject:EventType):void
{
// Actions performed in response to the event go here.
}
eventSource.addEventListener(EventType.EVENT_NAME, eventResponse);
This code does two things. First, it defines a function, which is the way to specify the actions you want 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. We'll consider each of these parts in more detail.
A function provides a way for you to group actions together, with a single name that is like a shortcut name to carry out the actions. A function is identical to a method except that it isn't necessarily associated with a specific class (in fact, a method could be defined as a function that is associated with a particular class). When you're creating a function for event handling, you must choose the name for the function (named eventResponse in this case), and you must also specify one parameter (named eventObject in this example). Specifying a function parameter is like declaring a variable, so you also have to indicate the data type of the parameter. There is an ActionScript class defined for each event, and the data type you specify for the function parameter is always the class associated with the particular event you want to respond to. Finally, between the opening and closing curly braces ({ ... }), you write the instructions you want the computer to carry out when the event happens.
Once you've written the event-handling function, you need to tell the event source object (the object that the event happens to--for example, the button) that you want your function to be called when the event happens. You do this by calling the addEventListener() method of that object (all objects that have events also have an addEventListener() method). The addEventListener() method takes two parameters:
Flash CS3
RSS feed | Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/9.0/main/00000021.html
Comments
sneakyimp said on Jan 21, 2008 at 10:02 PM : No screen name said on Jul 10, 2008 at 1:59 AM :