Shaun Mccran

My digital playground

19
M
A
Y
2008

Calling Javascript functions from Flex

I've tried several different ways of using JavaScript and flex together, mostly by imbedding the JavaScript into an ActionScript method, and calling that, which in turn invokes the JS.

This always seemed kind of messy to me, and wade the code very intermingled, it also meant that any changes to the JS meant re-compiling the Flex application.

After a little searching I found a better way!

Your JavaScript is written within your html template, and your Flex app uses the 'flash.external' package. This package allows the swf to call methods in the wrapper.

So in your Flex application

view plain print about
1<mx:Script>
2<![CDATA[
3import flash.external.ExternalInterface;
4
5/*
6Calls javascript on html page
7*/

8
9public function callExternalJS():void {
10var functionName:String = "doJS";
11var methodName:String = ExternalInterface.call(functionName, arguments);
12}
13]]>
14</mx:Script>

You can pass arguments in the regular JavaScript way of separating them with commas.

Call them in whichever way you need to IE:

view plain print about
1<mx:Button label="JS Function" click="callExternalJS()"/>

Then simply stick your JavaScript in your page like you would in normally!

view plain print about
1</script LANGUAGE="JavaScript">
2 function doJS()
3        {
4      // whatever
5 }
6</SCRIPT>

Make sure that your 'object' and 'embed' code has an 'id' attribute, otherwise it doesn't work.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Back to top