Welcome!

Adobe Flex Authors: Liz McMillan, RealWire News Distribution, Maureen O'Gara, Yakov Fain, Keith Swenson

Related Topics: Adobe Flex

Adobe Flex: Article

Designing Loosely Coupled Flex 2 Components

Powerful tools

The Flex data binding mechanism was used to show that properties defined in custom components can take advantage of data binding feature. The "lista" variable is a public property of custDataGrid custom component so we passed it to the custDataGrid tag declaration.

Similiarly, it's possibile to creata a data binding invoking a method of the custom component :

<mx:Label text="{custDG.justWrite()}" x="300" y="44"/>

The text attribute of the Label control will receive the text returned by the public function of custDataGrid custom component :

public function justWrite():String
    {
       return "This is a method of the component";
    }

The last step for designing a loosely coupled component is to handle the dispatching of an event that contains the return data. Each MXML custom component dipatches events that can be customized in 3 simple steps :

  • using the [Event] metadata tag
  • creating an event object
  • Dispatching the event and create the function to handle the event
The [Event] metadata tag defines the events that components can dispatch. It's possible to declare the [Event] metadata tag in an Actionscript classes, just after the package definition and above the class definition :

Package com.casario
{
[Event(name=" changeBlog", type=" flash.events.Event ")]
public class custComp
{

}
}

or in the <mx:Metadata> tag of an MXML file :

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

Once the [Event] metadata was created the component has to dispatch the event using the dispatchEvent() method. The dispatchEvent() method accepts the event object as argument as shown in the following code :

dispatchEvent(new Event("changeBlog"));

We modify our custDataGrid.mxml file to dispatch an event when the user clicks on an item of the datagrid. The main application will handle the event fired by the custom component and write some text in a Text Area control.

Open the custDataGrid.mxml with Flex Builder 2 and add the [Event] metadata tag as shown below:

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

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

<mx:Script>
   <![CDATA[
      import mx.collections.ArrayCollection;

      [Bindable]
      public var lista:ArrayCollection;

      public function justWrite():String
      {
        return "This is a method of the component";
      }

      private function changeHandler():void
      {
        dispatchEvent(new Event("changeBlog"));
      }
   ]]>
</mx:Script>

<mx:DataGrid id="myDG" dataProvider="{lista}" change="changeHandler()" >

</mx:DataGrid>

</mx:VBox>

The [Event] metadata defines a "changeBlog" event with a generic Event type and makes the event public so that the MXML compiler recognizes it :

<mx:Metadata>
[Event(name="changeBlog", type="flash.events.Event")]
</mx:Metadata>
The event is dispatched when the change event of the DataGrid is triggered :

<mx:DataGrid id="myDG" dataProvider="{lista}" change="changeHandler()" >

As you can see the "changeHandler" function simply executes the dispatchEvent() method :

private function changeHandler():void
      {
        dispatchEvent(new Event("changeBlog"));
      }

The main application has the role to handle the event triggered by the custom MXML component with a simple event handler function defined into the <mx:Script> block :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:cust="*">
<mx:Script>
   <![CDATA[
      import mx.collections.ArrayCollection;
      [Bindable]
      public var myData:ArrayCollection = new ArrayCollection (
      [{A:2000},{A:3000},{A:4000},{A:4000},{A:3000},{A:2000},{A:6000}]);

      private function changeBlogHandler (event:Event):void
      {
        myLabel2.text += "Event fired by Datagrid:"+ event.type + "\n" ;
      }

   ]]>
</mx:Script>
<cust:custDataGrid id="custDG" x="258" y="89" lista="{myData}" changeBlog="changeBlogHandler(event)"/>

<mx:Label text="{custDG.justWrite()}" id="myLabel" x="283" y="63"/>
   <mx:TextArea id="myLabel2" x="205" y="239" height="102" width="273"/>
</mx:Application>
The custDataGrid component fires the "changeBlog" event and associates an event handler function to it :
<cust:custDataGrid id="custDG" x="258" y="89" lista="{myData}" changeBlog="changeBlogHandler(event)"/>

The changeBlogHandler function takes the event object as argument and prints a simple text into the TextArea control :

private function changeBlogHandler (event:Event):void
      {
        myLabel2.text += "Event fired by Datagrid:"+ event.type + "\n" ;
      }

Observe the use of the event object with the syntax event.type that returns the type of the event triggers (in the example it returns changeblog as value ! )

NOTE: Flex Builder 2 automatically finds the reference to the the custom event defined into the component and shows it with the code hint :'

[fig. flexbuilder_customEvent.png] Flex Builder 2 identifies the event name

While we have seen how simple it is to create a custom event for our loosely coupled component, but this approach also has some limitations if we want to send data to the custom event. The fact is that the flash.events.Event class doesn't permit developers to add properties to it.

In fact we use the dispatch event just to notify that something happened in the MXML custom component. But what if we need to send complex data to a custom event ?

No need to be worried. This is done by creating custom event classes with Actionscript ! I'll show you how to develop custom event classes with a real example !


More Stories By Marco Casario

Marco Casario is CEO of Comtaste, a company devoted to develop Rich Internet Applications on the Web and for mobile devices.

He collaborates intensively with Adobe Italy as a speaker at conferences and as a consultant for Flash, Flex, and Flash Lite.

Learn more about Marco Casario at his blog http://casario.blogs.com. In 2005, Marco has founded Comtaste, a company dedicated to exploring new frontiers in Rich Internet Applications and the convergence between the web and the world of mobile devices — MobyMobile and YouThru are representative of their recent work. He is founder of the biggest worldwide Flash Lite User Group and of www.augitaly.com, a reference point for the Italian community of Adobe users, in which he carries out the role of Channel Manager for the section dedicated to Flex.

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
saravanan 11/23/07 12:44:26 AM EST

HI,

this is exellent tutorials..i have learned lot about using custom events in MXML and AS

But one more thing there is no change event for datagrid please check it , use some valid event for that ..