User Guide

Table Of Contents
Adding events to custom components 35
]]>
</mx:Script>
<greensquare id="myGS" mouseOver="changeAlpha(100);"
mouseOut="changeAlpha(startAlpha);" />
</mx:Application>
To handle an event that is not supported by the current parent class, such as a click event on a
UIObject, you must edit the component class file. However, to add a
click event to your
component, it is sometimes easier to extend the Button or SimpleButton class than it is to write
the code to support a
click event.
For information on defining new events and event handlers for your custom component, see
“Emitting events next.
Emitting events
You can define an event that is not inherited from the components parent class, such as a click for
a control that is not a subclass of the Button class. In the following example, Flex throws an error
because the Green Square component does not emit a
click event:
<greensquare id="myGS" click="changeAlpha(0);" />
If you try to use a click handler in the MXML file, you get an error similar to the following:
Error: unknown attribute 'click' on greensquare
This means that you have to go back to the component’s ActionScript class and tell the
component to emit a
click event. You do this by adding a call to dispatchEvent() in the
component’s ActionScript class file. You must also include the Event metadata keyword so that
Flex recognizes the dispatched event. For more information on the
dispatchEvent() method,
see Developing Flex Applications.
The following example adds a metadata keyword identifying
click as an event that this
component can emit, and then dispatches the
click event when the onRelease() method is
triggered. In this case, the
click event causes a change in the instance’s alpha property.
[Event("click")]
class greensquare extends mx.core.UIObject {
static var symbolName:String="greensquare";
static var symbolOwner:Object = greensquare;
var className:String = "greensquare";
function greensquare() {
}
function init() {
super.init();
invalidate();
}
function onRelease(Void):Void {
dispatchEvent({ type: "click" });