10
event

power to the user

pre-defined courses of action have their place, but the next level of programming involves more than just doing—we want to be reacting.

in order to allow for two-way communication between computer and user, we need to accept and respond to the user's input. but we don't control the user, so how do we know what they're going to do or when they're going to do it?

of course, we don't, and that's why interactivity can be so fun, we can write code that handles circumstances that were never pre-arranged.

event properties

when we give up control over timing, we must wait for a signal from the user to know when to react. we add a listener, an agent with an ear for just the type of event we're interested in.

the flash runtime monitors many situations, and when it detects something happening, it generates an Event instance containing some information about what just occured and sends it as a parameter to all functions that were added as listeners for that event type.

some common event types if we implement a function to act as an event listener, we can react whenever the event occurs
import flash.events.MouseEvent;
function onStageClicked(e:MouseEvent):void { trace("stage clicked"); }
stage.addEventListener(MouseEvent.CLICK, onStageClicked);

 

modeling and rendering state

events are commonly used to signal that a transition has been requested to move from one configuration, or state to another. representing application behavior as a collection of discrete states can be a useful technique for simplifying what can otherwise seem to be tricky inter-connected relationships.

diagrams

a state diagram is graph that shows all the possible modes or states an object can ever be in, and the triggers that will move the object from one state to another.

we can represent the behavior of a general toggle behavior, one good for lights, sounds, buttons, etc. with a simple state diagram:

how about a button rollover behavior? it's only slightly more complex with three states:

a garage door opener's behavior might be represented with four states like this:

machines

software or hardware that implements a state diagram is called a Finite State Machine, or FSM, because by definition its behavior is completely deterministic. there are only a finite number of states the machine may ever be in.

while not necessarily as 'smart' as artificial intelligence (AI), FSMs can often be easier to implement and test, and still provide complex and interesting behavior, especially if the state changing triggers are unpredictable.

as a simple example, we can implement the rollover behavior to create our own custom animated interactive cursor.
[.swf] [.fla]