Tuesday, May 26, 2009

Add an Event Listener in MXML

Flex components dispatch events whenever an action occurs, such as a user clicking a button, the selected item in a combo box changing, or data loading. To listen to these events being broadcast, simply add a reference to a function that will handle the event. For example:

Code View:




private function buttonClick():void
{
trace(" Button has been clicked ");
}

]]>








Adding click="buttonClick()" invokes the function buttonClick whenever the button dispatches a click event.

You can also pass the event object itself to the function. Every time a component dispatches an event, the component sends an object of type Event that any object listening to the event can receive. For example:

Code View:




private function buttonClick(event:Event):void
{
trace(event.target.id);
if(event.target.id == "buttonOne")
{
trace(" button one was clicked")
}
else
{
trace(" button two was clicked")
}
}

]]>


label="Click Me One" id="buttonOne"/>






By telling the event listener to listen for an object of type Event, you can send the event to the event listener and then respond to that event in different ways depending on specified criteria. In this example, the response depends on where the event originated.

The event object and the event dispatching system in Flex are some of the most important things to understand. All events contain a type that is used when the event is being listened for; if an event is of type click, then the event-listening method will be added to the click event of the child

No comments:

Post a Comment