Managing Your MouseEvents For Performance

Using MouseEvents in your projects is an inevitable thing. In very basic projects it’s not that important ( but it’s a good practice ) to manage your MouseEvents. You don’t want to have events that are active without being used. In medium / big projects should be a priority. Imagine you have many buttons or containers each having at last one event. Some buttons/ containers are not even displayed to the user until later. So why to have extra events active ? Let me give you an example: we have a button with mouse over effects and a click action.

_btn.addEventListener(MouseEvent.MOUSE_OVER,  BtnMouseEvents, false, 0, true);
_btn.addEventListener(MouseEvent.MOUSE_OUT,  BtnMouseEvents, false, 0, true);
_btn.addEventListener(MouseEvent.CLICK,       BtnMouseEvents, false, 0, true);

function BtnMouseEvents($e:MouseEvents):void
{
     switch($e.type)
     {
          case ”mouseOver”  : break;
          case ”mouseOut”   : break;
          case ”click”      : break;
     }
}

Wow,  three events for a button that it’s most likely that a user will not use. So what can we do to optimeze this situation ? Well … all we need is a single MouseEvent ( in this situation ).

_btn.addEventListener(MouseEvent.MOUSE_OVER, BtnMouseEvents, false, 0, true);

function BtnMouseEvents($e:MouseEvents):void
{
     switch($e.type)
     {
        case ”mouseOver” :
               _btn.removeEventListener(MouseEvent.MOUSE_OVER, BtnMouseEvents);
               _btn.addEventListener(MouseEvent.MOUSE_OUT,       BtnMouseEvents, false, 0, true);
               _btn.addEventListener(MouseEvent.CLICK,      BtnMouseEvents, false, 0, true);
               // actions
               break;

       case ”mouseOut”   :
              _btn.removeEventListener(MouseEvent.MOUSE_OUT,  BtnMouseEvents);
              _btn.addEventListener(MouseEvent.CLICK,             BtnMouseEvents, false, 0, true);
             _btn.addEventListener(MouseEvent.MOUSE_OVER,    BtnMouseEvents, false, 0, true);
              //actions
              break;

      case ”click”           : break;
   }
}

This was just an example. As you can see you only have one MouseEvent active all the time and two other when the button is used. It’s better than having three events running and not being used.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s