Sunday, June 26, 2011

Including and importing external Actionscript 3 files in Flex

In this tutorial we will learn about the ways of including external Actionscript documents in our Flex application.

We know how to write AS3 code in the mxml file itself, we simply have to include it in the fx:Script tags and the CDATA:

<fx:Script>
<![CDATA[
// AS3 code here
]]>
</fx:Script>

We could, however, write the code in an external file and then tell Flex that this is the script we're going to use. We can do that by giving a value to the source property of the fx:Script tag:

<fx:Script source="includes/myScript.as"/>

The myScript.as is not a package and it is not a class, so the structure of it is really basic. It could look like this, for example:

// myScript.as
public function sayHi():void{
trace("Hi!");
}

Another way to include files is using the include directive. We can also have some AS3 code and include some external files at the same time as well.

<fx:Script>
<![CDATA[
// AS3 code here (or not)
include "includes/myScript.as";
]]>
</fx:Script>

So, when compiling, Flex will just replace the 'include' line with all the code content in that included file.

There is including, and then there is importing in Flex. We can import external classes and packages. Well, this is done pretty much the same way as you would imagine - we just import the class as usual, and then refer to it as usual.

<fx:Script>
<![CDATA[
import myPackage.myClass;

private var something:myClass = new myClass();
]]>
</fx:Script>

And that's about it.

Thanks for reading!

No comments:

Post a Comment