What Is an Event?
Application programmers (the folks who make the everyday programs you use for Windows or Macintosh)
have long known that the key to graphical user interface (GUI) programming is events. So, what is an event,
and why are events so important? To answer that question, take a closer look at GUIs.
A GUI is, at its most base form, a large menu that lets the user choose what he wants to do. The problem is that
how the user does this choosing is based on a lot of complex interactions: keys being pressed, keys being
released, the mouse moving, a mouse button being pressed—you get the idea. Each one of these interactions is
an event. It occurs at a specific time and may have information associated with it. (The key that was pressed,
for example.) Now, events aren't limited to forms of user input. Things such as timers, network connections,
and file I/O also can create events. Basically, anytime you are working with something external to your code,
whether that is the hard disk, the user, or even time, you will be working with events.
Methods of Event Handling
There are two main methods to work with events in Flash MX: callbacks and listeners. Both have their
strengths and weaknesses as well as situations for which they are best suited. The most important thing to
remember about both methods is that organization and documentation are key to writing maintainable code.
Callbacks
The first method of working with events is known as a callback. Callbacks take advantage of the fact that
ActionScript is a highly forgiving language. In particular, callbacks execute a function that doesn't exist, and
Flash won't generate an error or even complain. Some forms of callbacks also utilize the fact that you can
overwrite any variable in Flash at any time, which includes functions.
The quick-and-dirty explanation of a callback is when an event occurs, the object that is the event's source tries
to execute a specific function. This may seem a bit confusing, but after you've read a bit more and seen them in
action, you'll see that callbacks are pretty simple.
A good example of a callback in action is the XML class. Now, I'm not going to get into the ins and outs of
XML quite yet, instead I'll go into how the XML class utilizes callbacks.
When you create an XML object your goal is to load XML formatted data into it from a source that can't
deliver the XML instantaneously, such as a hard disk, or more commonly for Flash, an Internet connection.
Therefore, your code needs to be able to deal with this latency. An XML object does this by using an event
callback.
No comments:
Post a Comment