Welcome!

Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex, PowerBuilder

Adobe Flex: Article

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="http://www.adobe.com/2006/mxml">
    
</mx:Button>

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 flash.events.Event.  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="http://www.adobe.com/2006/mxml"
    width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]"
    label="Add Item" fontSize="12" click="greenClickEventHandler()">
    
    <mx:Metadata>
        [Event(name="addItemEvent", type="flash.events.Event")]
    </mx:Metadata>
    
    <mx:Script>
        <![CDATA[
            private function greenClickEventHandler():void{
              trace("Ouch! I got clicked! Let me tell this to the world.");
            dispatchEvent(new Event("addItemEvent", true));// bubble to parent
            }
        ]]>
    </mx:Script>
</mx:Button>


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="http://www.adobe.com/2006/mxml"
    xmlns:ctrl="controls.*"   layout="absolute">
    
    <ctrl:LargeGreenButton addItemEvent="greenButtonHandler(event)"/>
        
    <mx:Script>
        <![CDATA[
            private function greenButtonHandler(event:Event):void{
                trace("Someone clicked on the Large Green Button!");
            }
        ]]>
    </mx:Script>
</mx:Application>

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="http://www.adobe.com/2006/mxml"
      backgroundColor="#ff0000"  creationComplete="init()">
        
    <mx:Script>
        <![CDATA[
            private function init():void{
                parent.addEventListener("addItemEvent",addItemToCartEventHandler);
            }
    
            private function addItemToCartEventHandler(event:Event){
                this.text+="Yes! Someone has put some item inside me, but I do not know what it is. \n";
            }
        ]]>
    </mx:Script>
</mx:TextArea>

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="http://www.adobe.com/2006/mxml" layout="vertical"
    xmlns:ctrl="controls.*"   xmlns:cart="cart.*">
    <ctrl:LargeGreenButton addItemEvent="greenButtonHandler(event)"/>
    <cart:BlindShoppingCart width="350" height="150" fontSize="14"/>
    <mx:Script>
        <![CDATA[
            private function greenButtonHandler(event:Event):void{
                trace("Someone clicked on the Large Green Button!");
            }
        ]]>
    </mx:Script>
</mx:Application>


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 flash.events.Event, 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 {
    import flash.events.Event;

    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   
            itemDescription=description;
        }

        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="http://www.adobe.com/2006/mxml"
      backgroundColor="#ff0000"  creationComplete="init()">
    
    <mx:Script>
        <![CDATA[
        private function init():void{
          parent.addEventListener(ItemAddedEvent.ITEMADDEDEVENT,addItemToCartEventHandler);
        }

        private function addItemToCartEventHandler(event:ItemAddedEvent){
          text+="Yes! Someone has put " + event.itemDescription + "\n";
        }
        ]]>
    </mx:Script>
</mx:TextArea>

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="http://www.adobe.com/2006/mxml" >
    
    <mx:Metadata>
        [Event(name="addItemEvent", type="flash.events.Event")]
    </mx:Metadata>
    <mx:Label  text="Item name:"/>
    <mx:TextInput id="enteredItem" width="300"/>
    <mx:Button
        width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]"
        label="Add Item" fontSize="12" click="greenClickEventHandler()"/>
    <mx:Script>
        <![CDATA[
            import cart.ItemAddedEvent;
            private function greenClickEventHandler():void{
                trace("Ouch! I got clicked! Let me tell this to the world.");
                dispatchEvent(new ItemAddedEvent(enteredItem.text));
            }
        ]]>
    </mx:Script>
</mx:HBox>

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="http://www.adobe.com/2006/mxml" layout="vertical"
    xmlns:ctrl="controls.*"   xmlns:cart="cart.*">
    <ctrl:NewItem />
    <cart:ShoppingCart width="350" height="150" fontSize="14"/>
</mx:Application>

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.

More Stories By 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 (http://yakovfain.com) 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

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
HamPhoneSwingTreeCart 11/09/07 11:33:53 AM EST

Nice article on event-driven programming.

A++++ Will deal with again.

@ThingsExpo Stories
"There's plenty of bandwidth out there but it's never in the right place. So what Cedexis does is uses data to work out the best pathways to get data from the origin to the person who wants to get it," explained Simon Jones, Evangelist and Head of Marketing at Cedexis, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Cloud Academy is an enterprise training platform for the cloud, specifically public clouds. We offer guided learning experiences on AWS, Azure, Google Cloud and all the surrounding methodologies and technologies that you need to know and your teams need to know in order to leverage the full benefits of the cloud," explained Alex Brower, VP of Marketing at Cloud Academy, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clar...
Large industrial manufacturing organizations are adopting the agile principles of cloud software companies. The industrial manufacturing development process has not scaled over time. Now that design CAD teams are geographically distributed, centralizing their work is key. With large multi-gigabyte projects, outdated tools have stifled industrial team agility, time-to-market milestones, and impacted P&L stakeholders.
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"MobiDev is a software development company and we do complex, custom software development for everybody from entrepreneurs to large enterprises," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
"IBM is really all in on blockchain. We take a look at sort of the history of blockchain ledger technologies. It started out with bitcoin, Ethereum, and IBM evaluated these particular blockchain technologies and found they were anonymous and permissionless and that many companies were looking for permissioned blockchain," stated René Bostic, Technical VP of the IBM Cloud Unit in North America, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Conventi...
SYS-CON Events announced today that Telecom Reseller has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5-7, 2018, at the Javits Center in New York, NY. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, discussed how from store operations and ...
In his session at 21st Cloud Expo, Carl J. Levine, Senior Technical Evangelist for NS1, will objectively discuss how DNS is used to solve Digital Transformation challenges in large SaaS applications, CDNs, AdTech platforms, and other demanding use cases. Carl J. Levine is the Senior Technical Evangelist for NS1. A veteran of the Internet Infrastructure space, he has over a decade of experience with startups, networking protocols and Internet infrastructure, combined with the unique ability to it...
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, introduced two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a multip...
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, whic...
SYS-CON Events announced today that Evatronix will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Evatronix SA offers comprehensive solutions in the design and implementation of electronic systems, in CAD / CAM deployment, and also is a designer and manufacturer of advanced 3D scanners for professional applications.
Leading companies, from the Global Fortune 500 to the smallest companies, are adopting hybrid cloud as the path to business advantage. Hybrid cloud depends on cloud services and on-premises infrastructure working in unison. Successful implementations require new levels of data mobility, enabled by an automated and seamless flow across on-premises and cloud resources. In his general session at 21st Cloud Expo, Greg Tevis, an IBM Storage Software Technical Strategist and Customer Solution Architec...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics gr...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things’). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing? IoT is not about the devices, it’s about the data consumed and generated. The devices are tools, mechanisms, conduits. In his session at Internet of Things at Cloud Expo | DXWor...