Calling Flex from JavaScript

To call Flex from JavaScript, you need to register a Flex method using the ExternalInterface class to make this method callable from JavaScript. Here I wanted to get hold of a JavaScript variable that is defined in the HTML wrapper (in my case, this variable defined the URL of a GPX file that I wanted to process in Flex).


<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="absolute"
  creationComplete="initApp();">
  <mx:Script>
	private var gpxUrl : String;
	public function setGpxDataSource(value:String):void {
 	    gpxUrl = value;
 	    loadData();
	}

        // Make the method setGpxDataSource callable from JavaScript.
	public function initApp() : void {
	    ExternalInterface.addCallback("setDataSource", setGpxDataSource);
	    var u:URLRequest = new URLRequest("javascript:getGpxUrl()");
	    navigateToURL(u,"_self");
	}
  </mx:Script>

This means that in the JavaScript portion of your application you wont be able to call the Flex method until the Flex component has been completely rendered. To get around this, after the Flex component has been completed, call a JavaScript method (using the navigateToURL method) that in turn will call Flex.

In the HTML wrapper, you need to define the JavaScript function that will call Flex. The object that you can use to invoke Flex is the object that is created via the embed/object tag. The name/id of this object is what you use to call the Flex method.


<html>
...
   <object
      classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
      id="flexRuutr" ...
     <embed name="flexRuutr" .../>
   />
...
<script>
    var gpxUrl = "http://javey.net/bike/gpx/18-nov-2007.gpx";
    function getGpxUrl() {
	flexRuutr.setDataSource(gpxUrl);
    }

</script>

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.