Not yet rated

Problem

I would like to have a single callback function that can handle callbacks for a variety of different types of events such as MouseEvent and TouchEvent.

Solution

Just use the same event listener function (or closure) for multiple event types. Instead of strictly typing the event object in the event listening function you type it as flash.events.Event which is the least common denominator in this case.

Detailed explanation

Just use the same event listener function (or closure) for multiple event types. Instead of strictly typing the event object in the event listening function you type it as flash.events.Event which is the least common denominator in this case (usually, you should always type your variables and parameters as strict as possible - but this is one of the use cases where you don't want it)

ui.addEventListener(TouchEvent.TOUCH_BEGIN, myHandler);
ui.addEventListener(MouseEvent.CLICK, myHandler);

private function eventHandler(event:Event)
{
  // your code here
}
  
 
to further distinguish between the concrete type of events you can use switch statements, e.g.
 
private function eventHandler(event:Event)
{
  switch (event.type)
  {
    case TouchEvent.TOUCH_BEGIN:
      // do whatever needs to be done here
      break;
    case MouseEvent.CLICK:
      // do whatever needs to be done here
      break;
  }
}
  

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes