AIR

June 3rd, 2012

Using Custom Events in Adobe Flex

More articles by »
Written by: Nouman Naveed
Tags:
adobe flex custom event

Using Flex is very easy and there are many features which will allow you to make communication between custom components easy. And Custom Events capability is one of the great facility of exchanging data between custom components and allowing you to expose your data to main application. In typical MVC architecture controller decides the flow of data and which model to update. Here your main application application file with <s:Application> tag is an controller. This flex application file will decide which model to update and how the data flows to other custom components.

Basically, we deal with two custom components in this article and we will understand custom events by taking these two component for our simplicity sake. Majority custom events are used to expose data to other components which could update the UI or just display the data coming from another component. We use concepts like source component (from which you are interested in getting data out) and destination component (receiving data from source). Both custom components will not have any knowledge of business logic written in other component. It is the responsibility of source component to expose data to controller and controller decided where to route the data. The data coming out from flex source component will be routed by controller (main application file) to flex destination component. This data can be simple string, number, boolean, array, ArrayCollection and custom object etc.

It is important to create custom event class which extends base class called Event, this event class is part of flash.events package. By extending you can add your own implementation in addition to existing default behavior of event class. Passing data between custom component is very simple when you follow proper steps of creating custom events.

Step 1 (Create Custom event class) – ProductEvent.as

  • Create a event class by extending flash.events.Event class.
  • Create your member variables depending upon the amount of data you want to hold and expose to destination component. These variables of class can be of any datatype.
  • Create constructor to have at least two parameters. First parameter will be a name of customEvent (could be your own name example: abc / xyz) and second will be holding data sent from a source custom component.
  • Override the clone() method if necessary and this will allow your custom event object to be available to all levels.

package events
{
import flash.events.Event;

import valueObjects.RProduct;

public class ProductEvent extends Event
{
public var product:Product;

public function ProductEvent(type:String,product:Product)
{
super(type);
this.product=product;
}
}
}

Step 2 (inside source component) – ChooseMenu_Comp.mxml

  • Create custom component from which you want to expose data and decide the amount of data you want to expose.
  • Use Event MetaData tag [Event] to denote your custom event name and type
  • Create a event object and pass data to constructor of your event class
  • Dispatch the event using dispatchEvent() function.

<?xml version=”1.0″ encoding=”utf-8″?>
<s:Group xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”>

<fx:Metadata>
[Event(name=”selectProduct”,type=”events.ProductEvent”)]
</fx:Metadata>

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

import mx.collections.ArrayCollection;

import spark.events.IndexChangeEvent;

[Bindable]
public var menuItems:ArrayCollection;

protected function list1_changeHandler(event:IndexChangeEvent):void
{
var eventObj:ProductEvent=new ProductEvent(“selectProduct”,event.target.selectedItem);
this.dispatchEvent(eventObj);
}
]]>
</fx:Script>

<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<s:List dataProvider=”{menuItems}”
labelField=”prodName”
change=”list1_changeHandler(event)”/>
</s:Group>

Step 3 (inside main application ) – Application_CustomEvent.mxml

  • Handle the custom event bubbling from source component and register the handler function in main application file.
  • Set your event object of handler as custom event class name.
  • Extract the data from event object
  • Inject the data from source component to public properties of destination custom component.

<?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”
minWidth=”955″ minHeight=”600″
creationComplete=”restService.send()”
xmlns:components=”components.*”>

<!– Properties of parent ======================================= –>

<s:layout>
<s:VerticalLayout paddingLeft=”25″ paddingTop=”25″/>
</s:layout>

<!– Script block ============================================== –>

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

import mx.collections.ArrayCollection;
import mx.rpc.events.ResultEvent;

import valueObjects.Product;

//variable declarations
[Bindable]
private var menuItems:ArrayCollection = new ArrayCollection();
[Bindable]
private var product:Product;

//event handlers
private function restaurantDataHandler(event:ResultEvent):void
{
var data:ArrayCollection = event.result.restaurant.item;
var rItem:Product;
var i:int;

for (i = 0; i < data.length; i++)
{
rItem = new Product();
rItem.idNo = data.getItemAt(i).idNo;
rItem.prodName = data.getItemAt(i).prodName;
rItem.description = data.getItemAt(i).description;
menuItems.addItem(rItem);
}
}

protected function choosemenu_selectProductHandler(event:ProductEvent):void
{
product=event.product;
}

]]>

</fx:Script>

<!– Declarations ============================================== –>

<fx:Declarations>
<s:HTTPService id=”restService”
url=”data/restaurant.xml”
result=”restaurantDataHandler(event)”/>
</fx:Declarations>

<!– UI components ============================================== –>

<components:ChooseMenu menuItems=”{menuItems}”
selectProduct=”choosemenu_selectProductHandler(event)”/>

<components:DisplayProduct product=”{product}”/>

</s:Application>

Step 4 (Destination Component) – DisplayProduct.mxml

  • Create public property to access data inside the component
  • Use public property to populate UI components or any components
  • Data is injected to this component from main application file (Application_CustomEvent.mxml)

<?xml version=”1.0″ encoding=”utf-8″?>
<s:Group xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”>

<fx:Script>
<![CDATA[
import valueObjects.RProduct;

[Bindable]
public var product:valueObjects.RProduct;
]]>
</fx:Script>

<s:layout>
<s:VerticalLayout/>
</s:layout>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>

<s:Label text=”Product Name: {product.prodName}”/>
<s:Label text=”Description: {product.description}”/>

</s:Group>

Data file for <s:HTTPService> can be downloaded here. Download Data File


About the Author

Nouman Naveed
My name is Mohammed Nouman Naveed. I work and play with Flash Platform technologies and has experience of 11 years. Consulting and Training is part of my job. I am Adobe Certified Instructor, Adobe User Group Manager, Adobe Certified Expert and Adobe Community Champion.




 
 

 
AIR
myimge

Adobe Flash Builder 4.7 Beta Available !

Recently Adobe released Adobe Flash Builder 4.7 beta which will support Adobe Flash 11.4 and Adobe AIR 3.4. It will also support Apache Flex 4.8 release. This version has improved workflow for iOS application development with s...
by Nouman Naveed
0

 
 
AIR
customize-datatips-for-flex-column-chart

Custom DataTip Renderers for ColumnChart

Flex provides many types of charts which allow raw data to show in meaningful format. ColumnChart component is one of the commonly used chart component in many flex applications. Customization of column chart datatip box is not...
by Nouman Naveed
0

 
 
AIR
flex-inspectable-metatag1

Using [inspectable] metatag

Every experienced Flex developer knows about [Bindable] & [Event] metatags. However, I was surprised to know that some developers don’t know the purpose of [inspectable] metatag. Here I am going to discuss purpose of ...
by Nouman Naveed
0

 

 
AIR
flexatom.com adobe certified

Get Adobe Certified

During my recent assignment client was asking many questions on certification process. Sotoday I have decided to add some light on how certification is acquired to make you proud.There are many quality resources already on the ...
by Nouman Naveed
1

 
 
AIR
adobe flex modules

Using Flex Moduls in your Application

Increasing application performance is very critical for anyone who is building mid-size to large application. It is seen in many applications that everything you have in your application is loaded on start-up. This loading of a...
by Nouman Naveed
0

 




0 Comments


Be the first to comment!


Leave a Reply

Your email address will not be published. Required fields are marked *