Search code examples
actionscript-3optimizationactionscript

Actionscript 3: Using MouseEvent.CLICK and TouchEvent.TOUCH_TAP


I implemented

MouseEvent.CLICK 

across my project to be used on touch and non touch devices. I am now using

TouchEvent.TOUCH_TAP 

as this is working better on touch screens.

However, this does not work on non touch devices. So I want to use whichever is appropriate to the platform. My project is deployed to mobile and desktop.

I am hoping a better way exists rather than covering my project in if statements!

if (mobile) {
  addEventListener(TouchEvent.TOUCH_TAP, closeClick);
} else {
  addEventListener(MouseEvent.CLICK, closeClick);
}

Solution

  • Like Organis suggested, I think defining your own global variable is a good way to do it. If it makes it easier to not have to worry about where and when to set the variable, you could also use a method, or even a getter method, like this:

    public class EventConfig
    {
        public static function get clickTap():String
        {
            return mobile ? TouchEvent.TOUCH_TAP : MouseEvent.CLICK;
        }
    

    Then you could listen like this:

    addEventListener(EventConfig.clickTap, myFunc);
    

    But beware, make sure your handler functions always have an Event parameter and not MouseEvent or TouchEvent, because you could cause silent failures by passing the wrong kind of event to those functions and there would be no way to catch those exceptions and you'd have a hard time figuring out what's going on.

    public function myFunc(e:Event):void
    

    As a side note, if you're interested in making separate builds for touch screen and mouse, you might look into FlashDevelop's conditional compilation. You could have a compiler constant that indicates which event type should be used.