Implement custom events in ActionScript 3.0
Post by efox | Date: 2008-09-08
In ActionScript 3.0 you can now create your own Events that extends the Event class.
package.events
{
public class CustomEvent extends Event
{
public static const CUSTOM_TYPE:String = "customType";
public var customProp:String;
public function CustomEvent( type:String, cp:String, bubbles:Boolean, cancelable:Boolean )
{
super( type, bubbles, cancelable )
customProp = cp;
}
}
}
This can be used like: dispatchEvent( new CustomEvent( CustomEvent.CUSTOM_TYPE, "myProp", true ) ); It works fine until you need to re-dispatch the event, If you do re-dispatch the event like below:
myDispatcher.addEventListener( CustomEvent.CUSTOM_TYPE, onCustomEvent );
private function onCustomEvent( event:CustomEvent ):void
{
dispatchEvent( event );
}
the event is cast back to the type Event. To solve this you need to override the clone method inside your custom event class. This will keep your event as its original type.
package.events
{
public class CustomEvent extends Event
{
public static const CUSTOM_TYPE:String = "customType";
public var customProp:String;
public function CustomEvent( type:String, cp:String, bubbles:Boolean, cancelable:Boolean )
{
super( type, bubbles, cancelable )
customProp = cp;
}
public override function clone():Event
{
return new CustomEvent( type, customProp, bubbles, cancelable );
}
}
}





Previous
Next
Tags: