Abdulcode

Pages

Jul 20, 2010

Flex: Creating custom events

All MXML components can dispatch events, either those inherited by the components from their superclasses, or new events that you define within your components. When you are developing MXML components, you can add your own event types.

In this example, you define a new component called MyText.mxml that uses a
tag as its root tag. This component also defines a new property called enableTI that users set to true to enable text input or to false to disable input.

The setter method dispatches a new event type, called enableEvent, when the value of the enableTI variable changes. The [Event] metadata tag identifies the event to the MXML compiler so that the file referencing the component can use the new property.

Syntax for the [Event] metadata tag:
 <mx:Metadata>
[Event(name="eventName", type="eventType")]
</mx:Metadata>

Example : /*MyText.mxml*/
<?xml version="1.0" encoding="utf-8"?>
<mx:TextInput xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Metadata>
[Event(name="enableEvent", type="flash.events.Event")]
</mx:Metadata>

<mx:Script>
<![CDATA[
public function set enableTI(bool:Boolean):void
{
this.enabled=bool;
dispatchEvent(new Event("enableEvent"));
}

public function get enableTI():Boolean
{
return this.enabled;
}
]]>
</mx:Script>

</mx:TextInput>

Example : /*Main.mxml*/
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
xmlns:abdul="com.abdul.*">

<mx:Script>
<![CDATA[
import mx.controls.Alert;

private function enableEventHandler(e:Event):void
{
Alert.show("Event Handler");
}
]]>
</mx:Script>

<abdul:MyText id="myText"
enableTI="true"
enableEvent="enableEventHandler(event);"/>

<mx:Button click="{myText.enableTI=!myText.enableTI}"/>

</mx:Application>

No comments:

Post a Comment