Thursday, June 23, 2011

Events in Flex: addEventListener() in Flex

In this tutorial we'll learn how to use addEventListener() to add event listeners for Flex components. In other words, we'll add listeners using AS3.

It is often easy to use inline script to set listeners for Flex components, but sometimes the components might be created dynamically, on the go, so sometimes it might be better to use addEventListener to add event listeners.

If you've read the previous tutorial, you already know what the creationComplete event is used for. I am going to set a listener for creationComplete event in the s:Application tag, so I can call a function once everything has done loading. The function is called init and is defined in the fx:Script block.

The init() method is called once the whole content has dispatched the creationComplete event:

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               creationComplete="init()">

We will just add a label and a button components as the content of the application.

<s:VGroup>
<s:Button label="Click me" id="myButton" />
<s:Label id="myLabel" />
</s:VGroup>

Now, we can add AS3 code to our application. In the init function we'll add the listener for our Button, and we'll also need to create an event handler function for it. Don't forget to import the MouseEvent class, as we are using it as the event type for the listener.

<fx:Script>
<![CDATA[
import flash.events.MouseEvent;

private function init():void{
myButton.addEventListener(MouseEvent.CLICK, onClick);
}

private function onClick(evt:MouseEvent):void{
myLabel.text = "Button clicked!";
}
]]>
</fx:Script>

Full code:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               creationComplete="init()">

<fx:Script>
<![CDATA[
import flash.events.MouseEvent;

private function init():void{
myButton.addEventListener(MouseEvent.CLICK, onClick);
}

private function onClick(evt:MouseEvent):void{
myLabel.text = "Button clicked!";
}
]]>
</fx:Script>

<s:VGroup>
<s:Button label="Click me" id="myButton" />
<s:Label id="myLabel" />
</s:VGroup>

</s:Application>

You can try if it works by clicking the button:



Thanks for reading!

Related:

Events in Flex: User Events
Events in Flex: System Events

No comments:

Post a Comment