Categories
Articles

AIR Flex Custom Events in a Component

A common error in creating custom events inside of a component is the dispatching of the event using the event type you have created in the the custom event.

In an application you may be dealing with events that are solely called from Actionscript and have no UI and event that are part of a UI.

In the case of events that have a UI you may create a component the UI and want to show the event in the code help and as part of the MXML tag. This is where your thinking can get crossed where you think in terms of event types in Actionscript only events.

Consider this custom event.

package com.who.events
{
	import flash.events.Event;
	
	public class MyCustomEvent extends Event
	{
		public static const STOP:String = "com.who.events.MyCustomEvent.stop";
		public function MyCustomEvent(type:String = STOP, bubbles:Boolean=false, cancelable:Boolean=false) 
		{
			super(type, bubbles, cancelable);
			
			
		}
		override public function clone():Event 
		{
			return new MyCustomEvent(type, bubbles, cancelable);
		}
	}
}

The event type is a package path name giving it a unique name.

To dispatch the event you might use this:

 
...
var myCustomEvent:MyCustomEvent= new MyCustomEvent(MyCustomEvent.STOP);
dispatchEvent(mainViewCallEvent);
...

This is the same as

	
...	
var myCustomEvent:MyCustomEvent= new MyCustomEvent("com.who.events.MyCustomEvent.stop");
dispatchEvent(mainViewCallEvent);
...

The code for listening to the event would be

	
...			
componentId.addEventListener(MyCustomEvent.STOP, eventHandlerMethodName,true,0,true);
...

Now you want include the event so it is part of the MXML of a component:

...
	<fx:Metadata>
		[Event(name="stop", type="com.who.events.MyCustomEvent")] 
		
	</fx:Metadata>
...

The name can be anything you want but the inclination is to use the name appended to the end of the type in the custom event class. In this case stop. However the event will not longer be seen. The fix is to change the creation of the event instance for dispatching.

...		
var myCustomEvent:MyCustomEvent= new MyCustomEvent("stop");
dispatchEvent(mainViewCallEvent);
...