Register Now!
Save $200
Register before October 17th to SAVE! ... and also receive a FREE copy of the Best-Selling AJAX Book, a $119 Value!
Untitled Document
2008 East
Platinum Sponsor
Untitled Document
2008 East Gold Sponsors
Untitled Document
2008 East Exhibitors
Untitled Document
2008 East Media Sponsors
Untitled Document
2008 Association Sponsor
2007 West Sponsors Conference Directory
2007 East Sponsors
Untitled Document
2008 SYS-CON Events

Can't Miss RSS Feed
Subscribe to the RSS Feed & Get All The Conference News As It Happens!

2008: Decision Year for RIAs - October 20-22, 2008 San Jose

Event-Driven Programming in Flex with Custom Events
Create loosely-couple components in Adobe Flex

From Farata Systems blog

Event-driven programming model offers an excellent architecture based on loosely-coupled components consuming and throwing events. This simply means that a properly designed component knows how to perform some functionality and notifies the outside world by broadcasting one or more custom events. I need to stress, that such component does not send these events to any other component(s). It just broadcast its “exciting news” the event dispatcher. If any other component is interested in processing this event, it must register a listener for this event.

Before explaining how to create an event-driven component let’s state how we are going to use them.  This is a typical scenario: MyApplication uses Component1 and Component2. Components do not know about each other. Any event-handling component should define this event inside. For example, Component1 dispatches this custom event sending out an instance of the Event object, which may or may not carry some additional component-specific data. MyApplication handles this custom event and if needed, communicates with Component2 with or without feeding it with data based on the results of the first component event.

We’ll create a “shopping cart” application that will include a main file and two components: the first a large green button, and the second one will be a red TextArea field. These components will be located in  two separate directories “controls” and “cart” respectively.

To create our first MXML component in Flex Builder, select the “controls”  directory and click on the menus File | New MXML Component. In the popup screen we’ll enter LargeGreenButton as a component name and we’ll pick Button from a dropdown as a base class for our component. Flex Builder will generate the following code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Button xmlns:mx="">

Next, we’ll make this button large, green and with rounded corners (just to give it a Web 2.0 look). This component will be dispatching an event named greenClickEvent. When? No rocket science here -  when someone clicks on the large and green.

Custom event in MXML are annotated within the Metadata tag in order to be visible to MXML. In the listing below,  in the metadata tag [Event] we declare a custom event of generic type  Since the purpose of this component is to notify the sibling objects that someone has clicked on the button, we’ll define the event handler greenClickEventHandler() that will create and dispatch our custom event.

<?xml version="1.0" encoding="utf-8"?>
<mx:Button xmlns:mx=""
    width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]"
    label="Add Item" fontSize="12" click="greenClickEventHandler()">
        [Event(name="addItemEvent", type="")]
            private function greenClickEventHandler():void{
              trace("Ouch! I got clicked! Let me tell this to the world.");
            dispatchEvent(new Event("addItemEvent", true));// bubble to parent

Listing 1. LargeGreenButton.mxml

Please note, that the LargeGreenButton component has no idea of who will process its addItemEvent. It’s none of its business: loose coupling in action!

In dynamic languages following naming conventions. Common practice while creating custom components is to add the suffix “Event” to each of the custom events you declare, and the suffix ”Handler” to each of the event handler function.

Here’s the application that will use the LargeGreenButton component:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx=""
    xmlns:ctrl="controls.*"   layout="absolute">
    <ctrl:LargeGreenButton addItemEvent="greenButtonHandler(event)"/>
            private function greenButtonHandler(event:Event):void{
                trace("Someone clicked on the Large Green Button!");

Listing 2. EventApplication.mxml

We have defined an extra namespace “ctrl” here to make the content of “controls” directory visible to this application.  Run this application in the debug mode, and it’ll display the window below. When you click on the green button it will output on the console the following:

Ouch! I got clicked! Let me tell this to the world.
GreenApplication:Someone clicked on the Large Green Button.  

While adding attributes to <ctrl:LargeGreenButton>, please note that code hints work, and Flex Builder properly displays the greenClickEvent in the list of available events of new custom component button.


Figure 1. The output of GreenApplication.xmxl

Our next component will be called BlindShoppingCart. This time we’ll create a component in the “cart” directory based on the TextArea.

<?xml version="1.0" encoding="utf-8"?>
<mx:TextArea xmlns:mx=""
      backgroundColor="#ff0000"  creationComplete="init()">
            private function init():void{
            private function addItemToCartEventHandler(event:Event){
                this.text+="Yes! Someone has put some item inside me, but I do not know what it is. \n";

Listing 3. BlindShoppingCart.mxml

Please note, that the BlindShoppingCart component does not expose to the outside world any public properties or methods. It’s a black box. The only way for other components to add something to the cart is by dispatching the addItemEvent event.  The next question is how to map this event to the function that will process it.  When someone will instantiate the BlindShoppingCart, Flash Player will dispatch  the creationComplete event on the component, our code calls the private method init(), which adds an event listener mapping the addItemEvent to the function addItemToCartEventHandler. This function just appends the text “Yes! Someone has put …” to its red TextArea.

The application RedAndGreenApplication uses that uses these two components LargeGreenButton and BlindShoppingCart.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" layout="vertical"
    xmlns:ctrl="controls.*"   xmlns:cart="cart.*">
    <ctrl:LargeGreenButton addItemEvent="greenButtonHandler(event)"/>
    <cart:BlindShoppingCart width="350" height="150" fontSize="14"/>
            private function greenButtonHandler(event:Event):void{
                trace("Someone clicked on the Large Green Button!");

Listing 4. RedAndGreenApplicatoin.mxml

Let’s go through the sequence of its events:
When the green button is clicked, the greenButtonHandler is called and it creates and dispatches the addItemEvent event on itself. The event bubbles to the parent container(s) notifying all listening parties of the event. BlindShoppingCart listens for such event and responds with adding text. Run this application, click on the button, and the window should look as follows:

Figure 2. The output of RedAndGreenApplication.mxml

And one more time: the green button component shoots the event to the outside world without knowing anything about it. That is very different from the case when we would write “glue” code like cart.addEventListener(“click”, applicationResponseMethodDoingSomethingInsideTheCart).

Sending Data Using Custom Events

To make our blind shopping cart more useful, we need to be able not only to fire a custom event, but this event should deliver description of the item that was passed to shopping cart. To do this, we’ll need to create a custom event class with an attribute that will store application-specific data.  

This class has to extend, override its method clone to support event bubbling, and call the constructor of the super class passing the type of the event as a parameter. The ActionScript class below defines a property itemDescription that will store the application-specific data.

package cart {

    public class ItemAddedEvent extends Event    {
        var itemDescription:String; //an item to be added to the cart
        public static const ITEMADDEDEVENT:String ="ItemAddedEvent";
        public function ItemAddedEvent(description:String )
            super(ITEMADDEDEVENT,true, true); //bubble by default   

        override public function clone():Event{
            return new ItemAddedEvent(itemDescription);  //  bubbling support inside
Listing 5. The custom event ItemAddedEvent

The new version of the shopping cart component is called ShoppingCart, and its event handler extracts the itemDescription from the received event and adds it to the text area.

<?xml version="1.0" encoding="utf-8"?>
<mx:TextArea xmlns:mx=""
      backgroundColor="#ff0000"  creationComplete="init()">
        private function init():void{

        private function addItemToCartEventHandler(event:ItemAddedEvent){
          text+="Yes! Someone has put " + event.itemDescription + "\n";

Listing 6. ShoppingCart.mxml

There is a design pattern called Inversion of Control or Dependency Injection, which means that an object does not ask other objects for required values, but rather assumes that someone will provide the required values from outside. This is also known as a Hollywood principle: ”Don’t call me, I’ll call you”.  Our ShoppingCart does exactly this – it waits until some unknown object will trigger event it listens to that will carry item description. Our component knows what to do with it, i.e. display in the red text area, validate against the inventory, send it over to the shipping department, and so on.

Next, we will completely rework our LargeGreenButton class into NewItem component - to include a label and a text field to enter some item description, andthe same old green button:
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox     xmlns:mx="" >
        [Event(name="addItemEvent", type="")]
    <mx:Label  text="Item name:"/>
    <mx:TextInput id="enteredItem" width="300"/>
        width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]"
        label="Add Item" fontSize="12" click="greenClickEventHandler()"/>
            import cart.ItemAddedEvent;
            private function greenClickEventHandler():void{
                trace("Ouch! I got clicked! Let me tell this to the world.");
                dispatchEvent(new ItemAddedEvent(enteredItem.text));

When we look at our new application with new ShoppingCart and NewItem components, it is almost indistinguishable from the original one. If we would of kept the old class names, we could of used the old application.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="" layout="vertical"
    xmlns:ctrl="controls.*"   xmlns:cart="cart.*">
    <ctrl:NewItem />
    <cart:ShoppingCart width="350" height="150" fontSize="14"/>

Listing 7. RedAndGreenApplication2.mxml

When the user enters the item description and clicks the green one, the application creates a new instance of the ItemAddedEvent, passing the entered item to its constructor, and the ShoppingCart properly properly displays selected ”New Item to Add” on the red carpet.

Figure 3. The output of the RedAndGreenApplication.mxml

Making components loosely bound simplifies development and distribution but comes at higher cost during testing/maintenance times. Depending on delivery timeline, size and lifespan of your application you would have to make a choice between loosely coupled or strongly typed components. One last note. The itemDescription in Listing 2 does not have access level qualifier. It’s so called package level protection. The ShoppingCart can access itemDescription directly, but the classes outside of “cart” package can’t.

Event-driven programming is nothing new - we routinely did it in mid-nineties in such toos as PowerBuilder or Visual Basic. In Java, it also exists as an  implementation of Observer/Observable pattern. But entire Flex programming is built on events, which makes coding a lot simplier.

About Yakov Fain
Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs ( and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Nice article on event-driven programming.

A++++ Will deal with again.

Latest AJAXWorld RIA Stories
Enterprises are striving to become digital businesses for differentiated innovation and customer-centricity. Traditionally, they focused on digitizing processes and paper workflow. To be a disruptor and compete against new players, they need to gain insight into business data and...
Containers and Kubernetes allow for code portability across on-premise VMs, bare metal, or multiple cloud provider environments. Yet, despite this portability promise, developers may include configuration and application definitions that constrain or even eliminate application po...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing sm...
DXWorldEXPO LLC announced today that Ed Featherston has been named the "Tech Chair" of "FinTechEXPO - New York Blockchain Event" of CloudEXPO's 10-Year Anniversary Event which will take place on November 12-13, 2018 in New York City. CloudEXPO | DXWorldEXPO New York will present ...
Chris Matthieu is the President & CEO of Computes, inc. He brings 30 years of experience in development and launches of disruptive technologies to create new market opportunities as well as enhance enterprise product portfolios with emerging technologies. His most recent venture ...
Untitled Document

Call 201 802-3020 or Click Here to Save $200!

Register Today and
Save $200

Your registrations includes: Golden Pass Delegates will receive full conference access on October 20-22, 2008 including: Lunch and Coffee Breaks, Collectible Bag and Archives of all sessions on DVD. Includes access to all Conference Sessions including the Technical Sessions, Exhibits, Keynotes, Vendor Technology Presentations, and Power Panels.

Sponsorship Opportunities

AJAXWorld offers the undisputed best platform to position your company as a leading vendor in the fast-emerging marketplace for AJAX and Enterprise Web 2.0.

Please call

Who Should Attend?

 CTOs & VPs of Engineering
 Directors of Technology
 Sr. User Interface Architects
 Front-End Engineers
 VCs & Industry Analysts
 Directors of Business Development
 Software Engineers
 Senior Architects
 Application Programmers & Software Developers
 Project Managers
 Web Programmers & Designers
 Companies & Organizations that need to stay in
  front of the latest Web technology

AJAXWorld Security Bootcamp

Introducing at AJAXWorld RIA Conference 2008 West the world's first-ever full, one-day immersive "AJAX Security Bootcamp" - led by one of the world's foremost AJAX security experts and teachers, HP's Billy Hoffman.

View the full one-day schedule

AJAXWorld 2008 West - Tracks

Track 01: Enterprise RIAs
Track 02: Frameworks & Toolkits
Track 03: Web 2.0 & Mashups
Track 04: Hot Topics
Track 05: The Future of the Web
Track 06: iPhone Developer Summit

Brought To You By:

AJAXWorld Magazine is the pre-eminent independent vendor-neutral resource for the fastest growing new segment of the software business: entirely Web-based applications and experiences.

Download the Latest Issue!

AJAXWorld Webcasts


AJAXWorld Keynotes & Power Panels

2008 SYS-CON TV Keynotes: Can We Fix the Web? By Douglas Crockford - by Douglas Crockford
2008 SYS-CON TV Keynotes: 2008: The Year of the RIA - by Anthony Franco
2008 SYS-CON TV Power Panel: The Business Value of RIAs
2008 SYS-CON TV Power Panel: What Lies Beyond AJAX
2007 SYS-CON TV Keynotes: Why Web 2.0 for the Enterprise Is Far More Than Just a Facelift - by Ted Farrell
2007 SYS-CON TV Keynotes: Fueling the Next Generation Web: A Peek Behind the Green Curtain - by Bob Brewin
2007 SYS-CON TV Keynotes: AJAX in the Balance - by Joe Stagner

AJAXWorld Sessions on SYS-CON.TV

· Bill Scott - Yahoo! UI Library
· David Heinemeier Hansson - AJAX on Rails
· Jesse James Garrett - Elements of User Experience
· Dion Hinchcliffe - Real World AJAX
· Eric Miraglia - Open Source AJAX Development
· Paul Rademacher - Mashing Up Your Web Application
· Adam Sah - Google Gadgets
· Doug Crockford - An Introduction to JavaScript
· David Linthicum - Enterprise Web 2.0
· Patrick Grady - The Imagination & Experience Web

AJAXWorld...All The AJAX Rock Stars in One Spot!

Past Events Archive

SOAWorld Conference & Expo 2008 East
Virtualization Conference & Expo 2008 East
AJAXWorld 2008 Conference & Expo East
SOAWorld Conference & Expo 2007 West
Virtualization Conference & Expo 2007 West
AJAXWorld 2007 Conference & Expo West
SOAWorld Conference & Expo 2007 East
Virtualization Conference & Expo 2007 East
AJAXWorld 2007 Conference & Expo East
Other SYS-CON Events

Join Over 10,000 Early AJAX Adopters
Who Have Attended AJAXWorld
• A&R Edelman
• Academic Enterprise
• Accoona Corp [2 delegates]
• Acxiom
• Adams Capital Management
• Adaptive Edge
• Adaptive Path
• Adobe Systems Incorporated [21 delegates]
• Adobe Systems Romania
• Ajax13
• All Risks, Ltd.
• alliance
• Alliance For Community Care
• AlphaDetail Inc
• Altera Corporation
• [6 delegates]
• Appeon Corporation [2 delegates]
• Apple Computer [5 delegates]
• Apress [3 delegates]
• Arkivio
• Astute Solutions
• Avaya Inc [2 delegates]
• Avenda Systems
• Avenue A | Razorfish [3 delegates]
• Axcella, LLC [2 delegates]
• Aximsoft
• Azimyth
• Backbase USA Inc. [4 delegates]
• BAE Systems [2 delegates]
• Bank of America [2 delegates]
• Barkley Evergreen & Partners Interactive
• Bayview Financial [2 delegates]
• BEA Systems [3 delegates]
• Billeo
• BMC Software, Inc. [2 delegates]
• Borland Software Corporation
• Bradford Technologies, Inc [2 delegates]
• Brilliance
• Brocade Communications Systems, Inc. [2 delegates]
• Brookside Capital LLC
• Brulant
• Bungee Labs, Inc [6 delegates]
• Bureau of Labor Statistics
• BUZ Interactive
• Cadena Software
• Calix Networks
• Callidus Software [2 delegates]
• Cambia Security
• Carnegie Mellon West
• Cautella, Inc.
• Celequest [3 delegates]
• Change Vision, Inc.
• Charles E. Kenney, CPA
• Charles Schwab & Co., Inc. [8 delegates]



.NET Developer's Journal - .NETDJ   |   ColdFusion Developer's Journal - CFDJ   |   Eclipse Developer's Journal - EDJ   |   Enterprise Open Source Magazine - EOS
Open Web Developer's Journal - OPEN WEB   |   iPhone Developer's Journal - iPHONE   |   Virtualization - Virtualization   |   Java Developer's Journal - JDJ   |
PowerBuilder Developer's Journal - PBDJ   |   SEO / SEM Journal - SJ   |   SOAWorld Magazine - SOAWM   |   IT Solutions Guide - ITSG   |   Symbian Developer's Journal - SDJ
WebLogic Developer's Journal - WLDJ   |   WebSphere Journal - WJ   |   Wireless Business & Technology - WBT   |   XML-Journal - XMLJ   |   Internet Video - iTV
Flex Developer's Journal - Flex   |   AJAXWorld Magazine - AWM   |   Silverlight Developer's Journal - SLDJ   |   |   Web 2.0 Journal - WEB2

SYS-CON EVENTS  |  AJAXWorld Conference & Expo  |  iPhone Developer Summit  |  OpenWeb Developer Summit  |  SOA World Conference & Expo  |  Virtualization Conference & Expo
INTERNATIONAL SITES:   India  |  U.K.  |  Canada  |  Germany  |  France  |  Australia  |  Italy  |  Spain  |  Netherlands  |  Brazil  |  Belgium
 Terms of Use & Our Privacy Statement     About Newsfeeds / Video Feeds
Copyright ©1994-2008 SYS-CON Publications, Inc. All Rights Reserved. All marks are trademarks of SYS-CON Media.
Reproduction in whole or in part in any form or medium without express written permission of SYS-CON Publications, Inc. is prohibited.