Event metadata may be new to you. It specifies for the ActionScript component which events the component can dispatch. This allows you to write event handlers within your MXML code, as follows:
<StopWatch start=”output.text=’Starting…’ stop=”output.text=’Elapsed time: ‘+event.target.elapsedTime” />
The start event is dispatched the first time the user clicks anywhere on the component. An application that uses the StopWatch class can use this event to know when the user has started the stopwatch.
The stop event is dispatched when the user clicks the component a second time. An application that uses the StopWatch class can use this event to trigger another action.
The main feature of the StopWatch component is the ability for the user to click the mouse to start and stop the timer. You must capture the user’s click somehow. You capture the event with the createChildren() method; you set up your component to listen and handle click events on itself using the addEventListener() method. You specify the stateChange() method to handle the event.
The StopWatch class shows a simple example of using custom events. Whenever you think your component users need to know something about the component’s state, dispatch an event.
For example, if you look at the documentation for any Flex component, you’ll see that they dispatch a number of events. For example, most components dispatch the show event when they become visible. The more events you have, the more options a developer using your component has too.
The Analog Clock component has had no subcomponents or children. You created all of its elements (face and hands) from scratch. The StopWatch component, on the other hand, shows the time passing. The easiest way to add that functionality is to use a pre-existing text component, such as the Label component.
The Label component, called output, is created in the createChildren() method. You specify the Label component’s position in the layoutChildren() method.
Your component calls the stateChange() method whenever the user clicks the StopWatch component. The stateChange() method triggers the isStopped() switch and, depending on the new state of isStopped, either resets the clock to zero or uses the tickTock() method through an interval timer. In the StopWatch, the timer is set to go off every 100th of a second, rather than the one-second intervals in the AnalogClock.
The tickTock() method modifies the elapsed time and uses the positionHands() method from the AnalogClock base class. The tickTock() method also updates the Label component.
You can now build a component as fancy or as simple as you like. If you choose, you can make your component highly customizable. Let your imagination run wild!