Search Flex Components Free

Custom Search

December 27, 2007

Using ActionScript in Flex applications

ActionScript blocks can contain ActionScript functions and variable declarations when used in MXML applications.
Statements and expressions are only allowed if they are wrapped in a function. In addition, you cannot define new classes or interfaces in <mx:Script> blocks. All ActionScript in the blocks is added to the enclosing file's class when Flex compiles the application.
When using an <mx:Script> block, you must wrap the contents in a CDATA construct. This prevents the compiler from interpreting the contents of the script block as XML, and allows the ActionScript to be properly generated. As a result, Adobe recommends that you write all your <mx:Script> open and close tags as the following example shows:
<mx:Script>
<![CDATA[

]]>
</mx:Script>
The script within a given <mx:Script> tag is accessible from any component in the MXML file. The <mx:Script> tag must be located at the top level of the MXML file (within the Application tag or other top-level component tag). You can define multiple script blocks in your MXML files, but you should try to keep them in one location to improve readability.

The following example declares a variable and a function:


<?xml version=”1.0″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml “>
<mx:Script>
<![CDATA[
var z:Number;
public function doSomething():void {
z = z + 1; // This must be in a function.
ta1.text = z;
}
]]>
</mx:Script>
<mx:TextArea id=”ta1″ />
</mx:Application>

Including ActionScript code versus importing ActionScript classes
To make your MXML code more readable, you can also reference ActionScript files in your <mx:Script> tags, rather than insert large blocks of script. You can include or import ActionScript files.
There is a distinct difference between including and importing in ActionScript. Including is copying lines of code from one file into another. Importing is adding a reference to a class file or package so that you can access objects and properties defined by external classes. Files that you import must be found in the ActionScript classpath. Files that you include must be located relative to the application root or use an absolute path.
You use the include directive or the <mx:Script source=”filename”> tag to add ActionScript code snippets to your Flex applications.
You use import statements in an <mx:Script> block to add ActionScript classes and packages to your Flex applications.

Priority of ActionScript
Actionscript comes first.For example:
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”
http://www.adobe.com/2006/mxml ” layout=”absolute”
creationComplete=”init()”>
<mx:TextArea x=”21″ y=”10″ id=”aa”/>
<mx:TextArea x=”21″ y=”62″ id=”bb” text=”kanu wadhwa”/>
<mx:Script>
<![CDATA[
private function init():void{
aa.text = “hello”;
bb.text = “hi”;
}
]]>
</mx:Script>
</mx:Application>

Related Flex Tutorials