User Guide

Example: Creating a composite component 173
Example: Composite component
This section uses an example component, called ModalText and defined in the file
ModalText.as, that combines a Button control and a TextArea control. You use the Button
control to enable or disable text input in the TextArea control.
Defining event listeners for composite components
Custom components implement the createChildren() method to create children of the
component, as the following example shows:
override protected function createChildren():void {
super.createChildren();
// Create and initialize the TextArea control.
if (!text_mc) {
text_mc = new TextArea();
...
text_mc.addEventListener("change", handleChangeEvent);
addChild(text_mc);
}
// Create and initialize the Button control.
if (!mode_mc) {
mode_mc = new Button();
...
mode_mc.addEventListener("click", handleClickEvent);
addChild(mode_mc);
}
}
The createChildren() method also contains a call to the addEventListener() method to
register an event listener for the
change event generated by the Te x t Ar ea control, and for the
click event for the Button control. These event listeners are defined within the ModalText
class, as the following example shows:
// Handle events that are dispatched by the children.
private function handleChangeEvent(eventObj:Event):void {
dispatchEvent(new Event("change"));
}
// Handle events that are dispatched by the children.
private function handleClickEvent(eventObj:Event):void {
text_mc.editable = !text_mc.editable;
}
You can handle an event dispatched by a child of a composite component in the component.
In this example, the event listener for the Button control’s
click event is defined in the class
definition to toggle the
editable property of the TextArea control.