Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Integrating Flex into Ajax applications Skill Level: Intermediate Brice Mason (bmason@stegoworks.com) Principal Technologist Stegoworks LLC 15 Jul 2008 Traditional Asynchronous JavaScript + XML (Ajax) development continues to be the leading method for producing rich Internet applications (RIAs). However, the popularity of Adobe® Flex cannot be ignored. This article introduces the Adobe Flex Ajax Bridge (FABridge), a code library that enables an easy and consistent method for integrating Ajax and Flex content. By the end of this article, you'll be able to take advantage of the rich features available through Adobe Flash assets. Building Ajax applications has proven to be a consistent method for providing engaging applications. However, the explosion in popularity of Adobe Flex cannot be ignored. As we are continually pushed to create the best user experience, we're often faced with the difficult task of integrating Flash-based assets embedded in our Ajax applications. This article discusses the integration of Flash content with existing Ajax content using the FABridge, a code library developed by Adobe to handle this very task. To be an Ajax developer today is pretty special. We're always at the front lines, ready to greet users and offer the best first impression to the applications we build for them. As Web standards advance and more vendors decide to implement them, our jobs have become easier, allowing us to focus on the user experience. The further advancements in JavaScript frameworks such as Ext JS, jQuery, and Prototype have also allowed us to spend less time worrying about whether our code will work across the platforms we're asked to support, leaving more time to innovate. Although there are certainly more tools, techniques, and resources available to us today, there is also a shift in development methodology that serves as a push toward the rich world of Flash development. For many shops, the development workflow would involve the user interface (UI) group to produce designs that support a server-side-generated application. With just the JavaScript frameworks we have Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 15
  2. 2. developerWorks® ibm.com/developerWorks now, we're pushed in the direction of application development for the client side. However, the emergence of the Flex platform — a free, open source framework for producing Flash applications — brings us further into the application development arena. This type of innovation is good for us on the client side, but we must ensure that we handle the process of integrating it with current architectures in a thoughtful and careful manner. Before I introduce code samples showing how to work with Ajax and Flex assets, you need to understand the tools and skills required: • I produced the Ajax samples in this article using the Ext JS JavaScript library, so you need to download the .zip file that contains the library and supporting documentation. • Next, grab a copy of the free Adobe Flex 3 SDK and Adobe Flash Player 9 with debugging capability, if you don't already have it. • Although not required to follow along in this article, you may also want to check out at least a trial version of Adobe Flex Builder 3, an Eclipse-based IDE that enables rapid Flex application development in addition to superior debugging and profiling capabilities (see Resources). • Finally, a working knowledge of PHP is helpful. The integration issue If you were looking forward to replacing all your Ajax content with Flex assets, your task would be much simpler. However, this is an unlikely and often unreasonable approach, because there are many reasons to preserve traditional Ajax functionality. Fortunately, there's no reason you can't keep the best of both environments to produce a rich, cohesive application. There are quite a few simplistic methods for passing data to ActionScript code from the Flash container (HTML/JavaScript code), including the use of query strings and <param> tags. However, this method is limited to passing data into the container. A more powerful technique is to use the ExternalInterface class, an application program interface (API) used to broker communication between the ActionScript and JavaScript languages. The use of ExternalInterface is best demonstrated by the example in Listing 1: Listing 1. ExternalInterface example // ActionScript code function exposed():String { return "Hello, JavaScript!"; } Integrating Flex into Ajax applications Page 2 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  3. 3. ibm.com/developerWorks developerWorks® ExternalInterface.addCallback( "getActionScript", exposed ); // HTML/JavaScript code <script language="JavaScript"> var result = flashObject.getActionScript(); </script> <object id="flashObject" ...> <embed name="flashObject" ... /> </object> Listing 1 demonstrates a stripped-down example of how to use the ExternalInterface class to register an ActionScript function so that JavaScript code can call it. You do this by first defining an ActionScript function, then using the addCallback() method to expose the function to JavaScript for execution. On the HTML side, simply obtain a handle to the Flash container and call the function, which was named using the first parameter to the addCallback() method. Although this demonstration concentrated on exposing functions to the JavaScript code, you can just as easily go the other way by using the call() method of the ExternalInterface class. The ExternalInterface class can be quite powerful, but there are significant drawbacks to implementing it. To use ExternalInterface, you must be able to write code to implement both the ActionScript and JavaScript environments. This not only requires added skill but double the effort. In this situation, maintaining code as well as two very robust skill sets can become a challenge. To address the limitations of development against the Flash external API, Adobe has released the FABridge. The FABridge, which ships with the Flex SDK, is a small library used to expose Flash content to scripting in the browser and works in most major browser platforms. With the FABridge, plumbing code that was required to directly implement the Flash external API is now virtually eliminated. Further, the skills required to implement the bridge aren't as robust. As a JavaScript developer, you simply need to be able to understand what's available to you in the way of ActionScript properties and methods. Let's get started with a few examples that demonstrate the capabilities of the FABridge. An FABridge tutorial Before you get started using the FABridge, here are the materials and development environment you'll be working with. After downloading the latest Flex SDK, configure the directory structure shown in Listing 2: Listing 2. Directory structure for the FABridge tutorial Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 15
  4. 4. developerWorks® ibm.com/developerWorks / +--- bridge | +--- fabridge.js | +--- fabridge.as | +--- index.html The directory structure is straightforward: You just have an index page and the FABridge scripts hooked into their own directory named bridge. The location of the FABridge library files depends on your environment. Because I'm using Flex Builder 3 Professional on Mac OS X, my library files reside in install_root/sdks/frameworks/3.0.0/javascript/fabridge/. Now that you have the appropriate architecture in place, you can begin creating the skeletons on both the HTML/JavaScript and ActionScript sides. Use the code from Listing 3 to develop the HTML/JavaScript skeleton: Listing 3. HTML/JavaScript skeleton <html> <head> <title>FABridge Tutorial</title> <script type="text/javascript" src="bridge/FABridge.js"></script> <script type="text/javascript"> // ... </script> </head> <body> </body> </html> As you can see, you simply hook the FABridge JavaScript library to your code, and all the functionality of the bridge is immediately available. Next, use the code from Listing 4 to implement the bridge on the ActionScript side: Listing 4. Application skeleton <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:bridge="bridge.*" layout="absolute" width="300" height="142"> <bridge:FABridge bridgeName="flex" /> <mx:TextInput x="70" y="54" id="txt_test" text="FABridge rocks!"/> </mx:Application> This code might be a bit more unfamiliar to you. The UI is kept clean and simple by defining a single text input control with the ID txt_test and a default value of Integrating Flex into Ajax applications Page 4 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  5. 5. ibm.com/developerWorks developerWorks® FABridge rocks! The bridge namespace is defined, and all classes in the bridge directory are imported. Finally, the Flex application is given a name for the bridge to use to access it: flex. To compile this Flex code into a working SWF document, use the mxmlc utility from the Flex 3 SDK. The most basic compile command is shown in Listing 5: Listing 5. Compiling MXML path_to_flex_bin_folder/mxmlc path_to_mxml file The command in Listing 5 compiles the source file and outputs an SWF file with the same file name as the MXML in the same directory. Assuming a successful compilation, you can now hook the resulting SWF into your HTML file, as shown in Listing 6: Listing 6. Linking the resulting SWF file <embed src=”main.swf” /> Note: The code in Listing 6 is deliberately light to keep focus on the task of demonstrating the FABridge. Unless you're targeting a specific environment (Listing 6 is targeting Mozilla), you'll want to add more intelligence in the way of object tags and other load scripts. Assuming that all went well, your application should now look similar to Figure 1: Figure 1. The sample application Now that you have successfully compiled and linked the Flex application into the HTML container, invoke your first FABridge functions to obtain a reference to the Flex application. Use the code in Listing 7 to fill in the empty <script> tag in your HTML skeleton file: Listing 7. Obtaining a reference to the Flex application Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 15
  6. 6. developerWorks® ibm.com/developerWorks // global variable, holds reference to the Flex application var flexApp; var initCallback = function() { flexApp = FABridge.flex.root(); return; } // register the callback to load reference to the Flex app FABridge.addInitializationCallback( "flex", initCallback ); The code in Listing 7 starts by defining a global JavaScript variable that will hold a reference to the Flex application when the FABridge obtains it. A callback function is defined that sets the global variable and is invoked through the addInitializationCallback() FABridge method. Using this code is simply a matter of matching the name of the bridge that you configured in the Flex application. From here, you're able to access all sorts of ActionScript functionality from the JavaScript code. Working with ActionScript objects Now that you've obtained a global reference to the Flex application, you can access ActionScript objects through the consistent interface that the FABridge provides. In the ActionScript world, you would typically access objects through dot notation object.id. Rather than expose ActionScript objects in dot notation, however, the FABridge makes these objects available through function calls. It is a little different at first, but all you need to know is the template to follow. An object traditionally identified in ActionScript as object.id would now be accessed as object.getId(). This is best demonstrated through example: Type the code from Listing 8 into your HTML skeleton to try it out: Listing 8. Getting ActionScript objects by ID // get the text input control var txt = flexApp.getTxt_test(); The variable txt is an object that represents the text input control with the ID txt_test from the Flex application. You can see the template you would need to follow for gaining access to other ActionScript objects by ID. The declaration begins with the global reference to the Flex application, then a method call that always begins with the string get followed by the ID of the target object. Notice that the name of the ID must begin with a capital letter in this declaration. Getting and setting the properties of ActionScript objects is similar to the process just used. Keeping up with our example of manipulating the text input control, use the code from Listing 9 to get and set the text property: Listing 9. Get and set ActionScript properties Integrating Flex into Ajax applications Page 6 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  7. 7. ibm.com/developerWorks developerWorks® alert( "old: " + txt.getText() ); txt.setText( "Reset!" ); alert( "new: " + txt.getText() ); The code in Listing 9 first alerts the original value of the text input control from the Flex application. By following the template described earlier, you can see that the text property is obtained through a function call, with the get string prepended and the property name camel cased. The set() method uses the same process but accepts a parameter used to configure the new value of the object. After the code in Listing 9 executes, you should see a screen similar to Figure 2: Figure 2. Setting ActionScript object properties Now, let's move on to the easiest manipulation of all: calling ActionScript object methods. This process requires no special considerations on your part. ActionScript object methods are used in JavaScript code just as they would be used in ActionScript code. The code in Listing 10 demonstrates the invocation of a method on your text input control: Listing 10. Invoking ActionScript methods txt.setVisible( false ); The code in Listing 10 sets the text input control in the Flex application to be invisible. The object can still be referenced and manipulated, it's just not physically visible. Between the ActionScript and JavaScript worlds, this is no change in the way the methods are invoked. One of the more powerful features of the FABridge is the ability to pass functions between JavaScript and ActionScript code. Check out the code in Listing 11, which dynamically copies the value of the text input in Flex to a <div> on the HTML/JavaScript side: Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 15
  8. 8. developerWorks® ibm.com/developerWorks Listing 11. Passing functions // define a function used as a callback to JavaScript var txtCallback = function( event ) { // get the object which fired the event var swf_source = event.getTarget(); document.getElementById( "copy" ).innerHTML = swf_source.getText(); return; } txt.addEventListener( "change", txtCallback ); The code in Listing 11 is a JavaScript callback function that's fired each time the text input control value from the Flex application changes. When the value changes, it is copied to a <div> tag with the ID copy. This type of functionality can be very powerful, especially when attempting any sort of integration work between Ajax and Flex content. With both environments relying heavily on events, it's key to be able to have them work together. The last feature this article explores is exception handling. By default, when you use try . . . catch blocks throughout your JavaScript code, you'll be able to at least access an error code that you can then look up in the online reference for ActionScript errors. This methodology certainly works, but during development, you want access to as much information up front as possible. While using the FABridge, you can get this information simply by installing Flash Player 9 with debugging. With this feature installed, you have access to line numbers, file names, error types, and stack traces. Use the code in Listing 12 to see an example: Listing 12. Exception handling try { alert( flexApp.throwsAnError() ); } catch( e ) { var msg = ""; for( var i in e ) { msg += i + " = " + e[i]; } alert( msg ); } An error is thrown from the code in Listing 12 because the method throwsAnError() does not exist. The code from the catch block outputs an alert that looks similar to Figure 3: Figure 3. Exception data Integrating Flex into Ajax applications Page 8 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  9. 9. ibm.com/developerWorks developerWorks® As you can see, this data is far more useful than a single error code and less work to troubleshoot. When you're working with complex integration issues between differing technologies such as JavaScript and ActionScript, you'll appreciate this extra help. Putting it all together So far, this article has taken a tutorial-type approach to showing the capabilities of the FABridge. Now it's time to use a real-world scenario to demonstrate its usefulness. As indicated earlier, you want to integrate and use the best of both the Ajax and Flex worlds. One of the components that really shines on the Flex side is its charting capability. Although it's not a free library, it is worth the added cost if you're looking to do some intense client-side application programming. The example you'll work with here is a combination of a PHP service that serves dummy data containing the number of messages received in certain categories for specific users. The data from the PHP service is loaded into a grid control using the Ext JS JavaScript framework, then the same data is pushed over the FABridge as a data provider to a pie chart in Flex. Start by taking at look at the PHP service in Listing 13: Listing 13. The PHP service <?php $users = array(); array_push( $users, "Paul" ); array_push( $users, "Nancy" ); array_push( $users, "Ned" ); array_push( $users, "Lucy" ); $email = array(); $email[ "email" ] = array(); $email[ "totalCount" ] = count( $users ); for( $i = 0; $i < count( $users ); $i++ ) { Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 15
  10. 10. developerWorks® ibm.com/developerWorks $tmp = array(); $tmp[ "user" ] = $users[$i]; $tmp[ "friends" ] = rand( 0, 100 ); $tmp[ "family" ] = rand( 0, 100 ); $tmp[ "spam" ] = rand( 0, 100 ); array_push( $email[ "email" ], $tmp ); } echo json_encode( $email ); ?> Note: The data in this service is hard coded and only meant to demonstrate the concept. Next, take a look at Listing 14, which is the MXML to generate the pie chart: Listing 14. Flex pie chart <?xml version="1.0"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:bridge="bridge.*" width="600" height="800"> <bridge:FABridge bridgeName="flex" /> <mx:Script> <![CDATA[ [Bindable] public var email:Object; private function displaySpam( data:Object, field:String, index:Number, percentValue:Number ):String { var temp:String= (" " + percentValue).substr(0,6); return data.user + ": " + 'n' + "Total Spam: " + data.spam + 'n' + temp + "%"; } ]]> </mx:Script> <mx:Panel title="Spam E-mail"> <mx:PieChart id="chart" height="100%" width="100%" paddingRight="5" paddingLeft="5" showDataTips="true" dataProvider="{email}"> <mx:series> <mx:PieSeries nameField="user" labelPosition="callout" field="spam" labelFunction="displaySpam"> </mx:PieSeries> </mx:series> </mx:PieChart> <mx:Legend dataProvider="{chart}"/> </mx:Panel> </mx:Application> This code was taken from the Adobe documentation and modified to fit the scenario Integrating Flex into Ajax applications Page 10 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  11. 11. ibm.com/developerWorks developerWorks® as well as configured for use with the FABridge. One thing to note here is that the variable named email is bindable, which means that any references to this data set will be updated automatically. This works great, because you'll be sending data over the bridge to this same variable, which is then used as the data provider to the pie chart. The last piece to this puzzle is the JavaScript code in Listing 15: Listing 15. Produce the grid, populate the chart <link rel="Stylesheet" type="text/css" href="../global/ext-2.0.2/resources/css/ext-all.css" /> <script type="text/javascript" src="bridge/FABridge.js"></script> <script type="text/javascript" src="../global/ext-2.0.2/adapter/ext/ext-base.js"></script> <script type="text/javascript" src="../global/ext-2.0.2/ext-all-debug.js"></script> <script type="text/javascript"> Ext.onReady( function() { // global variable, holds reference to the Flex application var flexApp; var initCallback = function() { flexApp = FABridge.flex.root(); // load the data store, grid, populate the pie chart from JavaScript initUI(); return; } // register the callback to load reference to the Flex app FABridge.addInitializationCallback( "flex", initCallback ); function initUI() { // create a data store using the PHP service var ds_email = new Ext.data.JsonStore( { url: "service.php", root: "email", fields: [ "user", "family", "friends", "spam" ] } ); // when the data store loads, update the pie chart ds_email.load( { callback: function( r, o, s ) { // send an array of objects over the bridge to fill in the pie chart var arr_email = new Array(); for( var i = 0; i < r.length; i++ ) { var tmp = new Object(); tmp.user = r[i].data.user; tmp.family = r[i].data.family; tmp.friends = r[i].data.friends; tmp.spam = r[i].data.spam; arr_email.push( tmp ); } Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 15
  12. 12. developerWorks® ibm.com/developerWorks flexApp.setEmail( arr_email ); } } ); // create a populate the grid. var grid_email = new Ext.grid.GridPanel( { title: "E-mail Count", store: ds_email, columns: [ { header: "User", dataIndex: "user" }, { header: "Family", dataIndex: "family" }, { header: "Friends", dataIndex: "friends" }, { header: "Spam", dataIndex: "spam" } ], height: 300, width: 450, renderTo: "grid-email" } ); } } ); </script> The first thing to notice about this code are the links to the Ext JS resources needed to make it work. After hooking in the default styles and debug scripts for Ext, an onReady block is configured. This block is executed only after a full Document Object Model (DOM) is ready. You should be familiar with the code used to populate the global flexApp variable with a reference to the Flex application. One addition to the callback is the execution of the initUI function. This function is used to create an Ext data store using the PHP service and to populate an Ext grid control using the resulting data in the store. When the Ext data store is loaded, a data structure is created and pushed over the FABridge so that the data binds as a data provider to the pie chart. The final product is shown in Figure 4: Figure 4. The final product Integrating Flex into Ajax applications Page 12 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  13. 13. ibm.com/developerWorks developerWorks® As you scan the data in the grid, it should match up with what's represented in the pie chart. This really is a powerful concept, and you can see the possibilities it has to offer. Although this was a single real-world example of how you might want to implement the FABridge, there are several other popular ways to use this library. Syncing security information for remote service authentication and techniques to consistently brand and personalize applications are just a couple of examples of how best to use the bridge. Conclusion Adobe Flex is an incredible technology that is just starting to reveal its true potential. However, no single product will solve all the wants and needs of developers and users, so it's important that we keep our minds open and explore the possibilities of integration using the FABridge. Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 15
  14. 14. developerWorks® ibm.com/developerWorks Resources Learn • Adobe Flex Resources: See a collection of documentation for Adobe Flex. • Ext JS Resources: Find documentation and tutorials for the Ext JS JavaScript framework. • Mastering Ajax: Read the developerWorks series for a comprehensive overview of Ajax. • Technology bookstore: Browse for books on these and other technical topics. • IBM technical events and webcasts: Stay current with developerWorks' Technical events and webcasts. • developerWorks Open source zone: Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products. Get products and technologies • Adobe Flex: Visit the Flex product page. • Ext JS: Download the Ext JS JavaScript framework. Discuss • Flex discussion forum: Join the Flex discussion. • Ext JS discussion forum: Join the Ext discussion. • developerWorks blogs: Participate in developerWorks blogs and get involved in the developerWorks community. About the author Brice Mason Brice Mason is a husband and father from Albany, New York. He is also a developer, writer, and speaker who frequently starts sentences with "Wouldn't it be cool if . . . ." When not spending time with his family, he can be found writing code and writing about code. Trademarks Integrating Flex into Ajax applications Page 14 of 15 © Copyright IBM Corporation 1994, 2008. All rights reserved.
  15. 15. ibm.com/developerWorks developerWorks® Adobe, the Adobe logo, PostScript, and the PostScript logo are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States, and/or other countries. Integrating Flex into Ajax applications © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 15