I have a custom component which uses custom events. I'd like to register event listeners with this component that listen for my custom events. I can do this programmatically by using the addEventListener() method, but I would like to be able to do this directly within my MXML component instead.
Use the [Event] metadata tag to identify the custom event to the MXML compiler. This will allow listeners for this event to be registered from directly within your MXML components.
When a component dispatches an event, an event listener must be registered in order for a handler to be invoked. We often see this done programmatically in ActionScript...
myButton.addEventListener(MouseEvent.CLICK, doSomething);
But we also see this done directly through the component itself...
<mx:Button id="myButton" click="doSomething()" />
However, when we have custom components using custom events, we must do some housekeeping to keep this functionality. Particularly, when I create a custom component which dispatches a custom event, I must identify with the Flex compiler that my component dispatches the event. This is done with the [Event] metadata tag. For instance, if I have a custom button component which dispatches a custom event, then within that component definition, I must identify the event with the [Event] metadata tag, like so...
package com.adobe.cookbook.flex.example
{
import flash.events.MouseEvent;
import mx.controls.Button;
// Identifies to the Flex compiler that this component dispatches a custom event.
[Event(name="onMyEvent", type="com.adobe.cookbook.flex.example.CustomEvent")]
public class CustomASButton extends Button
{
...
} // class declaration
} // package
...or, if my component is defined via MXML...
<?xml version="1.0" encoding="utf-8"?>
<mx:Button xmlns:mx="http://www.adobe.com/2006/mxml""
<!-- Identifies to the Flex compiler that this component dispatches a custom event. -->
<mx:Metadata>
[Event(name="onMyEvent", type="com.adobe.cookbook.flex.example.CustomEvent")]
</mx:Metadata>
...
</mx:Button>
Now that my [Event] metadata tag has identified my event to the compiler, I can now access it directly through my MXML component...
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" verticalAlign="middle" creationComplete="init()" xmlns:example="com.adobe.cookbook.flex.example.*">
...
<example:CustomASButton id="myASButton" label="My ActionScript Button" onMyEvent="doSomething(event)" />
<example:CustomMXMLButton id="myMXMLButton" label="My MXML Button" onMyEvent="doSomething(event)" />
</mx:Application>
Voila! Now you can access your events directly through your MXML component!