Friday, May 21, 2010

Event Listeners

One of the most powerful tools I've run across are Event Listeners.  In fact, I can safely say that, without Event Listeners, much of your application will appear lifeless.  Event Listeners allow your own drawn objects to respond to one another, to the mouse, to the keyboard, to events that happen outside them all (like a simple browser resize) and ultimately offer a means of providing interactivity.

I like to think of a listener as a link between a passive and an active.  You want the ball to roll, so you kick it.

The means by which a listener is associated with an object is through addition.  Specifically, most objects have a method called "addEventListener" which, simple enough, adds a listener - one triggered by a particular event.

There are different classes of Events.  There are generic Events (the browser resize mentioned earlier falls into this category), mouse-specific events (clicking is obvious, but also includes mouse-over and mouse out), and lots of others as well.  [Here] is the flash documentation for Events.

Making use of an Event Listener is fairly easy - the simplest requires knowing the object to which you would attach the listener (the ball), the event which you anticipate happening (the kick), and what you want to happen as a result (rolling).

Code samples:
Example with anonymous function
private function addButtonWithListener():void
{
  var button:TextSprite = new TextSprite();
  button.x = 50;
  button.y = 50;
  button.width = 10;
  button.height = 10;
  button.text = "blue!";
  addChild(button);

  button.addEventListener( MouseEvent.CLICK, function( m:MouseEvent):void
  {
      button.text = (button.text=="blue!") ? "red!" : "blue!";
  });
}

Example with a separate method (requiring a global button)
public class ListenerExample
{
    private var button:TextSprite;
  
    instantiateButton( 50, 50, 10, 10, "blue!" );
    addButtonListener();
  
    private function instantiateButton( _x:uint, _y:uint, _w:uint, _h:uint, initialText:String):void
    {
      button = new TextSprite();
      button.x = _x;
      button.y = _y;
      button.w = _w;
      button.h = _h;
      button.text = initialText;
      addChild( button );
    }

    private function addEventListener():void
    {
      button.addEventListener( MouseEvent.CLICK, toggleButtonText );
    }

    private function toggleButtonText( m:MouseEvent=null ):void
    {
      button.text = (button.text=="blue!") ? "red!" : "blue!";
    }
}

That should get you started.

Another, later post, will address removing event listeners.

No comments:

Post a Comment