Pages

Friday, February 11, 2011

AS3: How to create custom event dispatcher class

We can create custom event dispatcher class as given below:

SOURCE CODE
package 
{
  import flash.events.EventDispatcher;
  import flash.events.Event;

  /**
   * @file CDispatcher.as
   * @author Abhishek Kumar
   */
  public class CDispatcher extends EventDispatcher
  {
    public static var ACTION:String = "action";
    public static var ERROR:String = "error";

    private static var instance:CDispatcher = new CDispatcher();

    public function CDispatcher() 
    {
      if (instance) 
        throw new Error("Error: Instantiation failed!");
    }

    public static function getInstance():CDispatcher 
    {
      return instance;
    }

    public function dispatch(e:String, o:Object=null):void 
    {
      dispatchEvent(new CEvent(e, o));
    }
  }
}

USAGE
import CDispatcher;
import CEvent;

var oDispatcher:CDispatcher = CDispatcher.getInstance();
oDispatcher.addEventListener (CDispatcher.ACTION, actionHandler);
oDispatcher.addEventListener (CDispatcher.ERROR, errorHandler);

function actionHandler (e:CEvent):void
{
  trace ("actionHandler: " + e);
}

function errorHandler (e:CEvent):void
{
  trace ("errorHandler: " + e.data);
}

/* 
* Anywhere inside custom made class
*/

private var oDispatcher:CDispatcher;
oDispatcher = CDispatcher.getInstance();
oDispatcher.dispatch(CDispatcher.ACTION);
oDispatcher.dispatch(CDispatcher.ERROR, 'Error#007');

No comments:

Post a Comment