Integrating Flex into Ajax applications

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 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!";
}

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
/
+--- 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 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
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
// 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
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
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:


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
Exception data

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++ ) {
      $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 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 );
               }
					
               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
Final product

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.


Resources

Learn

Get products and technologies

  • Adobe Flex: Visit the Flex product page.
     
  • Ext JS: Download the Ext JS JavaScript framework.
     

Discuss

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.

ref:www.ibm.com/developerworks/web/library/wa-aj-flex/#ibm-pcon

vim中删除技巧

:%s/[Ctrl-v][Enter]//g 删除DOS方式的回车^M
:%s= *$== 删除行尾空白
:%!sort -u 删除重复行
:%s/^.{-}pdf/new.pdf/ 只是删除第一个pdf
:%s/// 删除多行注释
:g/^$/d 删除所有空行 
:g!/^dd/d 删除不含字符串'dd'的行
:v/^dd/d 删除不含字符串'dd'的行
:g/str1/,/str2/d 删除所有第一个含str1到第一个含str2之间的行
:v/./.,/./-1join 压缩空行
:g/^$/,/./-j 压缩空行
ndw 或 ndW 删除光标处开始及其后的 n-1 个字符。
d0 删至行首。
d$ 删至行尾。
ndd 删除当前行及其后 n-1 行。
x 或 X 删除一个字符。
Ctrl+u 删除输入方式下所输入的文本。
D 删除到行尾
x,y 删除与复制包含高亮区
dl 删除当前字符(与x命令功能相同)
d0 删除到某一行的开始位置
d^ 删除到某一行的第一个字符位置(不包括空格或TAB字符)
dw 删除到某个单词的结尾位置
d3w 删除到第三个单词的结尾位置
db 删除到某个单词的开始位置
dW 删除到某个以空格作为分隔符的单词的结尾位置
dB 删除到某个以空格作为分隔符的单词的开始位置
d7B 删除到前面7个以空格作为分隔符的单词的开始位置
d) 删除到某个语句的结尾位置
d4) 删除到第四个语句的结尾位置
d( 删除到某个语句的开始位置
d) 删除到某个段落的结尾位置
d{ 删除到某个段落的开始位置
d7{ 删除到当前段落起始位置之前的第7个段落位置
dd 删除当前行
d/text 删除从文本中出现“text”中所指定字样的位置,一直向前直到下一个该字样所出现的位置(但不包括该字样)之间的内容
dfc 删除从文本中出现字符“c”的位置,一直向前直到下一个该字符所出现的位置(包括该字符)之间的内容
dtc 删除当前行直到下一个字符“c”所出现位置之间的内容
D 删除到某一行的结尾
d$ 删除到某一行的结尾
5dd 删除从当前行所开始的5行内容
dL 删除直到屏幕上最后一行的内容
dH 删除直到屏幕上第一行的内容
dG 删除直到工作缓存区结尾的内容
d1G 删除直到工作缓存区开始的内容

ref:wiki.ubuntu.org.cn/UbuntuSkills#unzip_.E4.B8.AD.E6.96.87.E6.96.87.E4.BB.B6.E5.90.8D.E4.B9.B1.E7.A0.81