Using ActionScript 3 SWFs with Flex 2

Awhile ago I wrote an article, Using ActionScript 2 SWFs with Flex 2. In that article I showed how you can communicate between a SWF written with ActionScript 2 and a Flex 2 SWF, written in ActionScript 3. The communication is done with LocalConnection as if the two SWFs were in separate Flash Players. That is effectively true since each SWF is put into its own virtual machine within the Flash Player.

With the release of Flash© CS3 you no longer have to use LocalConnection. Flash CS3 can create ActionScript 3 SWFs which are loaded into the same Flash Player virtual machine as a Flex 2 SWF. If you compare the two examples you’ll see this new method is clean and very easy to implement.

Download the Example
Get Flash CS3

Let’s start with the Flash SWF. I used the same Flash movie as I did in the earlier article, but this time I’ve updated it for ActionScript 3. If you open the FLA file and examine the ActionScript code, you will not see LocalConnection anywhere. Instead, you’ll see this:

function rotateStar( angle:Number ) : void {
  star_mc.rotation = angle;
}

function zoomStar( factor:Number ) : void {
  star_mc.scaleX = factor;
  star_mc.scaleY = factor;
}

function stopPlanet() : void
{
  stop();
}

function resumePlanet() : void
{
  play();
}

function getStar() : MovieClip
{
  return star_mc;
}

The functions, on the root timeline of the Flash Movie, can be directly called from Flex. In Flex, the SWF is loaded into a SWFLoader control:

<mx:SWFLoader width="300" height="300"
    
id=”flashStar”
    
source=”star_flash.swf”
    
complete=”starLoaded()” />

To rotate the star by 45 degrees, the Flex application calls the MovieClip’s rotateStar root timeline function:

var c:MovieClip = flashStar.content as MovieClip;
c.rotateStar( 45 );

The SWFLoader’s content property is the SWF’s root timeline. You cast the content property to MovieClip and then just call the functions defined.

Compare the code between the two examples. If you use Flash SWFs in your Flex applications, download Flash CS3 right away and simplfy your code.