Learning Flex – Lesson 5, Handling Events

Flex Events come in two types, user events (such as clicking a mouse or pressing a key) and system events (such as a component changing visibility or finishing instantiation).

Event handlers can be specified within a component tag in MXML for instance, a click event for a button could be handled like this –

<mx:Button id="myButton" click="myButton.label='clicked!'"/>

Flex expects an ActionScript  expression in this case and the single quotes are used to define the string within the overall handler expression.

Other than for trivial tasks, event handlers are normally written as ActionScript functions that may be defined externally or within a Script block. These are then called from the event handler spec such as click="clickHandler()".

Writing ActionScript code within a Script tag requires CDATA escaping as the ActionScript code is not valid XML. This is achieved by wrapping it with <![CDATA[ and ]]> so it is ignored by the XML parser.

Passing parameters to the handler is achieved by placing values between the parentheses. In the handler function, the passed value is given a type so the compiler knows what to expect. An example would be:

private function clickHandler(display:String):void
myButton.label = display;
<mx:Button id="myButton" click="clickHandler('clicked!')"/>

Creation Complete Event

An example of a system event is CreationComplete which is fired when a component has been initialized and placed in the application. The component will be visible at this time unless it’s visible property is false.

The CreationComplete event of a container is fired when it’s children have all broadcast their CreationComplete events and this process continues up the chain all the way to the final Application object.

This means that if we have components within a container, the order of event dispatch would be the components first, then the container, then the application.

Event Objects

Flex creates an event object each time an event is dispatched. This object contains information about the event that occurred. This object is often passed to the event handler so it may access properties from it.

The base event class is used as the common denominator for more specific event classes. This means that all event types have some common properties including type – the type of event that was fired and target which is a reference to the component object that caused the event.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: