Chapter 7. Create an Event Handler

ActionScript is an event-driven language. This means that in order for anything to occur in your script, an event must be triggered by Flash Player. Events can be triggered by the system or by the user. Examples of system events include an external file finishing being loaded or the play head entering a frame. User-triggered events include the user moving his or her mouse, clicking the mouse button, or pressing a key on the keyboard.

You need two pieces in your code to deal with events: an event handler and an event listener. An event handler is nothing more than a function that describes what will occur when the event is triggered. Event handlers can calculate a total, increase a user's score, submit information to a Web server, restart a movie, or almost anything else you need it to do. Event listeners allow you to register an event with a particular object in your movie. Listeners will be covered in the following sections.

All event handlers take a single argument, a reference to the event. As with all function arguments, you can give it any name that you want, although event and e are the two most common. The argument should be data-typed based on the type of event, so if the event will be triggered by the user clicking the mouse, you would use a type MouseEvent.

Event handlers can never return data, which makes sense if you consider that they are not being called by a line in the code that could continue processing but are instead being triggered by some action. Therefore, a handler's return type will always be void.

Create an Event Handler

  • Create an Event Handler
  • Create an Event Handler
  • Create an Event Handler
    Create an Event Handler
  • Create an Event Handler
  • Create an Event Handler
  • Create an Event Handler
  • Create an Event Handler
  • Create an Event Handler
  • Create an Event Handler
    Create an Event Handler
  • Create an Event Handler

    The event is created. In order to trigger the event, you will need to create an event listener, which is covered in the next two sections.

Extra

The ActionScript Event class provides a superclass for all the event types. Although it is possible to use the generic Event class for all events, it is better to rely on one of the 34 more specific subclasses of Event, as they provide more detailed properties and methods for the events. For example, MouseEvent is a subclass to use for all events involving mouse actions, including clicks, double-clicks, drags, and mouse movements. Unlike the Event class, MouseEvent includes specific properties to, among other things, detect the exact location of the mouse pointer. The KeyboardEvent class contains a property that allows you to detect which key was pressed, enabling you to respond to events differently depending on the key. Keyboard events are covered in Chapter 14.

You cannot pass other arguments to the event handler. However, it is possible to access details of the object being clicked through the event's target property, which will be discussed later in this chapter in the section "Using the Target Property."

Call an Event from a Button

Event handlers define the actions that you want to take when an event occurs, but like all functions, they must be called. An event listener enables you to specify the object and the event that will call the handler.

You can register an object with a handler by calling the addEventListener method. The method takes two arguments: the event that will provide the trigger and the handler to be called. The event could use the generic Event class, which can handle any event, but it is better to use a specific subclass of Event, such as MouseEvent. Most of these subclasses have defined constants for certain common events, so for instance, you can use MouseEvent.CLICK to call a handler when the user clicks the mouse button. The KeyboardEvent class likewise defines constants for most of the keys on the keyboard so that it can respond accordingly.

The name of the handler for the event is provided as the second argument of the function. Even though the handler is a function, you will always call it without the set of parentheses normally used when calling functions, as you cannot pass any arguments to the function. An example of calling the addEventListener on a button might look like this, in which an event handler gotoHome is called:

btHomeButton.addEventListener(MouseEvent.
 CLICK, gotoHome);

After the event listener has been added to the object and the event handler written, the object simply waits for the event to occur. When it does, the object calls the specified handler, which assumes processing at that point and performs whatever actions are required of it.

Call an Event from a Button

  • Call an Event from a Button
  • Call an Event from a Button

    Note

    See Chapter 3 for details on creating buttons and naming instances.

    Call an Event from a Button
  • Call an Event from a Button

    Note

    See Chapter 1 for details on opening the panel.

  • Call an Event from a Button

    Note

    For details, see the preceding section, "Create an Event Handler."

  • Call an Event from a Button
  • Call an Event from a Button
  • Call an Event from a Button
  • Call an Event from a Button
    Call an Event from a Button
  • Call an Event from a Button

    The movie plays in Flash Player.

  • Call an Event from a Button

    The event is triggered, and the event handler's code runs.

  • Call an Event from a Button

Extra

If you have a button nested within a MovieClip, the user will actually be clicking both objects simultaneously. Most of the time, you will add the event listener to the button. As the MovieClip would not have a listener for that event, it would ignore it. However, it is possible to have a listener attached to the MovieClip as well. If the clip's listener called the same handler as the button's, the handler would be called twice: once by the button and then a second time by the clip. You could, though, have the clip call a different handler, which would execute immediately following the button. In theory, there is no real limit to this effect, so if you had a button within a MovieClip that is itself nested within another MovieClip, each of the three objects could call event handlers. This process is known in ActionScript as "event bubbling" — the event "bubbles" up through the various objects, and each can be used to handle it if needed.

Define Events in a Custom Class

When you create a custom class, you have the opportunity to add an event listener and handler to the class itself, freeing you from having to repeatedly add the event code to individual instances. For example, say you were creating a complex application, and throughout various phases of the application, you wanted to provide a button that linked to a help resource. You could simply create a button symbol and place an instance of the symbol on the Stage whenever you needed it. However, you would then need to be sure to name each instance of the "help" button and then go into your code each time and add an event listener to that specific instance:

btHelp.addEventListener(MouseEvent.CLICK,
 helpHandler);

You could instead create a custom class that represented the button, and then you could add the event listener and handler within the code for the class itself. That way, the event would become a built-in part of the class and would be automatically applied to each instance, without you having to even think about it. You could then be assured that anytime you added an instance of the button, it would be able to automatically link to the help resource.

The process for doing this is simple: Just add the event handler within the class file and then call the addEventListener method to the class within its constructor. Remember that you can reference the class itself with the this keyword. As the event listener is being added in the constructor, it will be added to each instance as it is created.

Define Events in a Custom Class

  • Define Events in a Custom Class

    Note

    See Chapter 6 for details on creating custom classes.

    Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class

    Note

    See the section "Create an Event Handler."

  • Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class
  • Define Events in a Custom Class

    Note

    See Chapter 6 for details on creating MovieClips as instances of custom classes.

    Define Events in a Custom Class
  • Define Events in a Custom Class

    The movie plays.

  • Define Events in a Custom Class

    The event is called.

  • Define Events in a Custom Class

Extra

You need to be sure to import the appropriate event class into your custom class code, just as you need to do any other time you are using any of the built-in ActionScript classes within your custom class. All event classes are in the flash.events package, so for example, if you want to add a click event, you would need to import flash.events.MouseEvent. If you are unsure of the package to import, you can simply search for the event class in a search engine such as Google. One of the first few results will invariably be the official ActionScript documentation for the event, which will display the package name.

Adding an event listener to a custom class does not prevent you from adding other listeners to an instance of the class. You might have a listener and handler for a click event defined in the class but then allow a particular instance of the class to be dragged and thus need to listen for the drag event on that instance. You could even in theory have two separate handlers for the same event: one in the class and the other on the instance. In this scenario, both handlers would be called, with the class handler called first, followed by the instance's.

Remove Event Listeners

In certain situations, you may need to remove an event listener from an object. For example, you may have a game in which you want to allow your user to click an object only once and then have the object be either removed from the game or disabled. You may have a Flash-based Web site with a navigation bar and want to disable the button that links to the current state of the movie. Or you may want to disable a button on a form if you have written form validation code and need to prevent the user from trying to submit the form again until he or she fixes the errors.

You can remove an event listener from an event by calling the removeEventListener method. As with addEventListener, this method takes two arguments: the type of event and the handler being removed:

myClip.removeEventListener(MouseEvent.CLICK,
 handleClick);

After an event listener has been removed, the object will no longer respond to the event, but you can easily restore the listener by simply calling addEventListener on the instance again. Often, an event listener will be removed by the handler itself, so a handler responding to a click event might remove the listener to itself to prevent the same click event from triggering again.

Be careful to ensure that the event and the handler in the removeEventListener call are identical to those given in the corresponding addEventListener call. Otherwise, an event other than the one you expected may be removed, causing either an error or, more likely, unexpected behavior within your project. In the example shown here, an event handler on a button will, as part of handling the event, remove the listener so that the button can be clicked only once.

Remove Event LIsteners

  • Remove Event LIsteners
  • Remove Event LIsteners

    Nothing happens because the event handler removed the listener, preventing the handler from being called again.

Extra

It is a good idea to remove event listeners whenever you no longer need them. A considerable amount of programmatic overhead is consumed by event listeners, so having listeners still active in your code long after their purpose has been rendered moot is simply a waste of resources. As an example, if you have a navigation system that contains multiple levels of links but allows only the top level and a single sublevel to be clicked at any time, then you would want to remove the event listeners from the other sublevels to prevent them from consuming the additional resources when you do not want them active anyway.

This problem is particularly troublesome in game applications. In a typical shooting game, you would presumably have targets as instances of a custom class. They would each have an event listener attached. When a target is "destroyed" and removed from the game, its event listener would remain, consuming resources no longer needed.

Using the Target Property

The addEventListener method requires that you call an event handler as a simple string, using just the function's name. It does not provide a method whereby you can call it as a function name and pass arguments to it. Most of the time, this will not pose a problem. If you simply need to perform an action when a button is clicked, there really is no other information that needs to be sent.

However, there are certain situations in which you may need to at least determine which item was clicked. For example, if you had a calculator and provided a button for each of the basic mathematical operators but wanted to handle the calculation with a single event handler, you would need to determine which of the four buttons was clicked.

The Event class provides a target property for this exact situation. The target contains a reference to the object that triggered the event. In turn, it contains a series of properties to identify the object. For example, you can determine the name of the instance of the object using event.target.name, assuming that the event argument being passed to the function is called event.

Other properties of the object being clicked may be available through target. For example, the location of a clicked MovieClip would be accessible through event.target.x and event.target.y, and the text property of a text field can be accessed in a handler with event.target.text. You can also set writable properties, so you could have a handler rotate a MovieClip with event.target.rotation += 45, which would set the rotation to the current rotation plus 45 degrees, causing the clip to rotate 45 degrees each time it was clicked.

Using the Target Property

  • Using the Target Property
  • Using the Target Property
    Using the Target Property
  • Using the Target Property
  • Using the Target Property
  • Using the Target Property
  • Using the Target Property

    Note

    See Chapter 3 for details on creating symbols and naming instances.

    Using the Target Property
  • Using the Target Property

    The movie plays.

  • Using the Target Property

    The event handler triggers.

  • Using the Target Property

Extra

A second property, currentTarget, also exists within the event object passed to the handler. Most of the time, target and currentTarget will be the same. Technically, however, they can refer to two different objects. The target is the object that was actually the focus of the event, whereas currentTarget refers to the object that is currently listening for the event. If you simply have a button on the Stage and click it, then the target will be the button, and because the button is likewise listening for the event, it will also be currentTarget. However, if you nest the button within a MovieClip and then add the event listener not to the button but rather the clip, target will be the button — the item that was actually clicked — but currentTarget will actually be the object that is listening for the event — in this case, the clip. Odds are that you will rarely if ever have to make this distinction, but it is worth being aware of it in case you do.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.30.253