Tuesday, February 15, 2011

Exchange data between Actionscript 3 and Javascript - communication bridge

Exchange data between Actionscript 3 and Javascript - communication bridge:

Today we will learn how to exchange data between Actionscript 3 and Javascript, we will create a communication bridge using the ExternalInterface class.

In my example, there is going to be a numeric value in flash, which can be increased using javascript code.

Firstly, create a textfield in flash called myField and a button called myButton.

Here is the code for the flash file:

var myVar:Number = 0;
myField.text = myVar.toString();

ExternalInterface.addCallback('sendToAS', getFromJS);

function getFromJS(dir):void
{
myVar += dir;
myField.text = myVar.toString();
}

myButton.addEventListener(MouseEvent.CLICK, sendToJS);

function sendToJS(MouseEvent):void
{
ExternalInterface.call('receiveAS', myVar);
}

We use 2 methods of ExternalInterface class - call and addCallback. The addCallback is used for receiving stuff from JS, for example, the JS code asks the flash to perform a 'sendToAS' action. The flash receives the request and then looks at it - if the request is 'sendToAS', then perform a function called getFromJS [...]

No comments:

Post a Comment