TALKING WITH JAVASCRIPT AND HTML: WEB PAGE INTEGRATION
295
Calling from JavaScript Into Flex
Now that you know how to call from Flex into JavaScript, you need to learn how to go the other way. To
demonstrate, you will allow the JavaScript on the page to dynamically add items to a Flex control using an
addItem method that you will export through the ExternalInterface.
Following is the code for this JavaScript-driven Flex application:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="1024" minHeight="768"
creationComplete="creationCompleteHandler()">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
private var itemsList:ArrayCollection= new ArrayCollection();
protected function creationCompleteHandler():void
{
ExternalInterface.addCallback( "addItem",
function(str:String):void {
itemsList.addItem(str);
list.dataProvider = itemsList;
});
ExternalInterface.call( 'jscallinLoaded' );
}
]]>
</fx:Script>
<s:List id="list" width="200" height="250" />
</s:Application>
The Flex application is fairly simple. When it starts up, it registers the addItem method as a function that
will add an item to an array and then update the dataProvider on the list with the new array.
The Flex application then calls the jscallinLoaded function in the JavaScript code to let it know that the
Flash application has been loaded successfully.
The JavaScript code on the page that uses this Flex application is shown in the following code:
<script>
function jscallinLoaded()
{
document.getElementById( 'JavaScriptCallingFlexExample' ).
addItem( 'Carrots' );
document.getElementById( 'JavaScriptCallingFlexExample' ).
addItem( 'Corn' );

Get AdvancED Flex 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.