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
SYS-CON Events announced today that Dasher Technologies 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. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion 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. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, 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. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
SYS-CON Events announced today that TidalScale 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. TidalScale is the leading provider of Software-Defined Servers that bring flexibility to modern data centers by right-sizing servers on the fly to fit any data set or workload. TidalScale’s award-winning inverse hypervisor technology combines multiple commodity servers (including their ass...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they b...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
In a recent survey, Sumo Logic surveyed 1,500 customers who employ cloud services such as Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP). According to the survey, a quarter of the respondents have already deployed Docker containers and nearly as many (23 percent) are employing the AWS Lambda serverless computing framework. It’s clear: serverless is here to stay. The adoption does come with some needed changes, within both application development and operations. Tha...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, 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. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of 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. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.