2009-08-17

Custom Events in Action Script

You have an custom actionscript 3.0 class and it does all sorts of great thing, but now you want other people to be able to use it. There are many ways to do this but for this example I am going to create a custom event. Lets get started.

First add the following imports to your class.

import flash.events.Event;
import flash.events.EventDispatcher;

Then add the metadata about the custom event, the event in this example is called customEvent.

[Event(name="customEvent", type="flash.events.Event")]

Next copy and paste the following code anywhere into your class this is used to add the functions need to create event listeners and dispatch events.

private var disp:EventDispatcher;
public function addEventListener(type:String, listener:Function, useCapture:Boolean=false, 
 priority:int=0, useWeakReference:Boolean=false):void {
   if (disp == null) disp = new EventDispatcher();
   disp.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
    
public function removeEventListener(type:String, listener:Function, useCapture:Boolean=false):void {
 if (disp == null) return;
   disp.removeEventListener(type, listener, useCapture);
}
    
public function dispatchEvent(event:Event):void {
 if (disp == null) return;
   disp.dispatchEvent(event);
}

Next you need to add the code to fire your custom event to do this add the following code to the function you want to fire the event.

var deviceDataEventObject:DeviceDataEvent = new Event("customEvent");
dispatchEvent(deviceDataEventObject);

OK you custom class can now fire your custom event all you need to do is set up a event listener in the calling class, use this code.

customClass.addEventListener("customEvent", yourFunction);
private function yourFunction(event:Event):void{
   //Do Something here
}

Thats it you are done simple huh?