Wednesday, June 16, 2010

Flex Javascript Integration

Flex Javascript Integration

ExternalInterface defines two especially important static functions:
  • call( functionName:String, ... arguments ) - call a container function
  • addCallback( functionName:String, closure:Function ) - expose a Flex function to the container 
 

Call Browser/JavaScript from ActionScript

// call a JavaScript function defined in the container page
   var result:String = 
      ExternalInterface.call( "doSomethingInJavaScript", arg1, arg2 );
The above ActionScript code could call the below JavaScript code in  the container HTML page:
 
// a JavaScript function in the container HTML page
function doSomethingInJavaScript( arg1, arg2 )
   {
      // do something
      return "results for " + arg1 + " and " + arg2;
   }

Call ActionScript from JavaScript/Browser

public function init():void
   {
      // expose an ActionScript function to the container
      ExternalInterface.addCallback( "doSomethingInActionScript", doSomethingInActionScript );
   }
   
   // function now callable from JavaScript
   public function doSomethingInActionScript( arg1:String, arg2:Number ):String
   {
      return "result";
   }
 
The below JavaScript code can be used to call the exposed ActionScript 
function:
 
// get the Flex application (Flash object)
   var isIE = navigator.appName.indexOf("Microsoft") != -1;
   var flashName = "flashObjectName";
   var flashObject = (isIE) ? parent.Main.window[flashName] : document[flashName];
   
   if( flashObject )
   {
      // call the Flex application (Flash object)
      flashObject.doSomethingInActionScript( "arg1", 2 );
   }
 

 

 


No comments:

Post a Comment