Calling Javascript functions from Flash

Calling Javascript functions from Flash is very easy. We use a class called ExternalInterface. Here is ActionScript code:

import flash.external.*;
import flash.events.Event;

button1.addEventListener(MouseEvent.CLICK, buttonHandle);

function buttonHandle(event:MouseEvent)
{
    ExternalInterface.call("showMessage");
}

Here flash.external is a package where the class ExternalInterface is found.
The code is very simple. Event listener to button is added. And call is a method of ExternalInterface class, the parameter passed to call() is a name of the Javascript function.

The Javascript function is an alert message:

function showMessage()
{
    alert("Hi from flash");
}

Javascript function called from Flash

My first Flex program

Flex is important tool to develop Rich Internet Applications(RIA). RIAs can be developed using Ajax, OpenLaszlo, Silverlight(??) etc. Today I started working on Flex and created my first Flex program. The example is simple. There is a Panel with a Textfield and a Button. Whenever a button is clicked or when enter is pressed on the textfield, a message appears with the content of the textfield.

The code is as follows:

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Panel id=”panel” title=”Flex” ><mx:VBox id=”vbox” verticalAlign=”middle” horizontalAlign=”center” width=”203″ height=”84″>

<mx:TextInput id=”txtName” text=”Enter Something” enabled=”true” enter=”btnClicked()” />
<mx:Button id=”btnClick” label=”Click here” click=”btnClicked()”/>

</mx:VBox>
</mx:Panel>
<mx:Script>

<![CDATA[
import mx.controls.Alert;
public function btnClicked():void
{
    Alert.show( txtName.text );
}

]]>



The beautiful output:

blog11.png

blog21.png