Calling Flex Function From JavaScript


 

Calling Flex Function From JavaScript

Sometimes, you may need to call flex function from JavaScript to pass value in the flex application

Sometimes, you may need to call flex function from JavaScript to pass value in the flex application

Calling Flex Function From JavaScript

Sometimes, you may need to call flex function from JavaScript to pass value in the flex application. For this you need to register flex function using addCallback() function  of ExternalInterface to make the flex function callable from javascript.

ExternalInterface.addCallback("flexFunction", flexFunction);

The function addCallback() takes the first parameter as the alias name of the function which will be used by JavaScript to call the flex function, and the second parameter is the actual name of the flex function.

<?xml version="1.0"?>

<!-- wrapper/AddCallbackExample.mxml -->

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">

<mx:Script>

<![CDATA[

import mx.controls.Alert;

import flash.external.*;

public function init():void {

ExternalInterface.addCallback("flexFunction", flexFunction);

}

public function flexFunction(strFromJS:String):void {

Alert.show(strFromJS);

}

]]>

</mx:Script>

</mx:Application>

To Call Flex method from JavaScript do the following:

1. Add javascript code in html file where this swf file is embed. For example:

<script language="JavaScript">

function callFlexFunction() {

CallingFlexFunctionFromJavaScript.flexFunction(document.getElementById("name").value);

}

</script>


Here CallingFlexFunctionFromJavaScript is the reference to the swf object i.e. id and name properties of the 'object' and 'embed' tags. This reference is used to call the flex function.

2. Add html code in html file where this swf file is embed. For example:

<input type="text" id="name"/>

<input type="button" value="Display my name in Flex" onclick="callFlexFunction()">

When you open the html file in browser, it displays swf file and some html components. When you type some text in text box and click the button, you will see the output as below:

Ads