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.




 
 

 
CQ5
adobe aem56 dam logo

Setting Images in DAM

All images are loaded into the DAM (Digital Assets Management). To upload an image, you’ll need to use your Activator login. From the tree, click +Digital Assets Find the way to the tree to suitable folder (AAFP, images, ANN,...
by Nouman Naveed
0

 
 
 

Apache Flex 4.10.0 Available

Here comes Apache Flex 4.10. This project, the all-volunteer group of developers, and stakeholders in the development framework, today announced the release of Apache Flex 4.10.0. This release makes some important improvements ...
by Nouman Naveed
0

 
 
CQ5
aem 5.6.1 features pic

Many New Features in AEM 5.6.1

AEM 5.6.1 is a easy to use, unified experience management collection for marketers in the digital sphere to use in creating, managing, and delivering unique online experiences that are brand-entered and increase demand across d...
by Nouman Naveed
0

 

 
CQ5
Adobe CQ5 WEM, SOCO, Tagging, DAM

What’s New in CQ 5.6

1: It’s called AEM (Adobe Experience Manager) now Though I guess not that essential, it’s going to be exciting if the name is going to attach – there were other occasions where Adobe tried to rename this result and at the...
by Nouman Naveed
0

 
 
CQ5
content management for web and mobile

Content Management for Web & Mobile

Adobe CQ is a WCM and gives a better browser-based user interface. It is best suitable for business and IT for creating interactive, multimedia rich, multichannel consumer understanding to make an engaging digital existence, ma...
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 *