Using ActionScript in applications

Flex developers can use ActionScript to implement custom behavior within their applications. You first use MXML tags to declare things like the containers, controls, effects, formatters, validators, and web services that your application requires, and to lay out its user interface. Each of these components provides the standard behavior you’d expect. For example, a button automatically highlights when you roll over it, without requiring you to write any ActionScript. But a declarative language like MXML is not appropriate for coding what you want to happen when the user clicks a button. For that, you need to use a procedural language like ActionScript, which offers executable methods, various types of storage variables, and flow control such as conditionals and loops. In a general sense, MXML implements the static aspects of your application, and ActionScript implements its dynamic aspects.

ActionScript is an object-oriented procedural programming language, based on the ECMAScript (ECMA-262) edition 4 draft language specification. You can use a variety of methods to mix ActionScript and MXML, including the following:

  • Define event listeners inside MXML event attributes.

  • Add script blocks using the <fx:Script> tag.

  • Include external ActionScript files.

  • Import ActionScript classes.

  • Create ActionScript components.

ActionScript compilation

Although a simple application can be written in a single MXML or ActionScript (AS) file, most applications will be broken into multiple files. For example, it is common to move the <fx:Script> and <fx:Style> blocks into separate AS and CSS files that the application then includes.

It is also common for an application to import custom MXML and ActionScript components. These must be defined in other files, and MXML components may put their own <fx:Script> blocks into yet more AS files that they include. Components may also be imported from precompiled SWC files rather than source code. Finally, SWF files containing executable code can also be embedded in an application. The end result of all these input files is a single SWF file.

The Flex compiler transforms the main MXML file and other files it includes into a single ActionScript class. As a result, you cannot define classes or use statements outside of functions in the MXML files and the included ActionScript files.

You can reference imported ActionScript classes from your MXML application files, and those classes are added to the final SWF file. When the transformation to an ActionScript file is complete, Flex links all the ActionScript components and includes those classes in the final SWF file.

About generated ActionScript

When you write an MXML file and compile it, the Flex compiler creates a class and generates ActionScript that the class uses. MXML tags and ActionScript are used by the resulting class in several ways. This information is useful for understanding what is happening in the background of the application.

An MXML application (a file that starts with the <s:Application> tag) defines a subclass of the Spark Application class. Similarly, an MXML component (a file that starts with some other component’s tag, such as <s:Button>) defines a subclass of that component.

The name of the subclass is the name of the file. The base class is the class of the top-level tag. An MXML application actually defines the following:

class MyApp extends Application

If MyButton.mxml starts with <s:Button>, you are actually defining the following:

class MyButton extends Button

The variable and function declarations in an <fx:Script> block define properties and methods of the subclass.

Setting an id property on a component instance within a class results in a public variable being autogenerated in the subclass that contains a reference to that component instance. For example, if the <s:Button id="myButton"/> tag is nested deeply inside several containers, you can still refer to it as myButton.

Event attributes become the bodies of autogenerated event listener methods in the subclass. For example:

<s:Button id="myButton" click="foo = 1; doSomething()">

becomes

private function __myButton_click(event:MouseEvent):void { 
    foo = 1; 
    doSomething() 
}

The event attributes become method bodies, so they can access the other properties and methods of the subclass.

All the ActionScript anywhere in an MXML file, whether in its <fx:Script> block or inside tags, executes with the this keyword referring to an instance of the subclass.

The public properties and methods of the class are accessible by ActionScript code in other components, as long as that code “dots down” (for example, myCheckoutAccordion.myAddressForm.firstNameTextInput.text) or reaches up using the parentDocument, parentApplication, or FlexGlobals.topLevelApplication properties to specify which component the property or method exists on.

Using ActionScript in MXML event handlers

One way to use ActionScript code in an application is to include it within the MXML tag’s event handler, as the following example shows:

<?xml version="1.0"?>
<!-- usingas/HelloWorldAS.mxml -->
<s:Application 
    xmlns:fx="http://ns.adobe.com/mxml/2009"    
    xmlns:mx="library://ns.adobe.com/flex/mx"     
    xmlns:s="library://ns.adobe.com/flex/spark">

    <s:layout> 
        <s:BasicLayout/> 
    </s:layout>

    <s:Panel title="My Application" height="128" x="226" y="24">
        <s:TextArea id="textarea1" width="155" x="0" y="0"/>
        <s:Button label="Click Me"
            click="textarea1.text='Hello World';" 
            width="92" 
            x="31.5" y="56"/>
    </s:Panel>
</s:Application>

The executing SWF file for the previous example is shown below:

In this example, you include ActionScript code for the body of the click event handler of the Button control. The MXML compiler takes the attribute click="..." and generates the following event handler method:

public function __myButton_click(event:MouseEvent):void { 
    textarea1.text='Hello World'; 
}

When the user clicks the button, this code sets the value of the TextArea control’s text property to the String "Hello World." In most cases, you do not need to look at the generated code, but it is useful to understand what happens when you write an inline event handler.

To see the generated code, set the value of the keep-generated-actionscript compiler option to true. The compiler then stores the *.as helper file in the /generated directory, which is a subdirectory of the location of the SWF file.

For more information about events, see Events. For more information on using the command-line compilers, see Flex compilers.

Using ActionScript blocks in MXML files

You use the <fx:Script> tag to insert an ActionScript block in an MXML file. ActionScript blocks can contain ActionScript functions and variable declarations used in MXML applications. Code inside <fx:Script> tags can also declare constants (with the const statement) and namespaces (with namespace), include ActionScript files (with include), import declarations (with import), and use namespaces (with use namespace).

The <fx:Script> tag must be a child of the <s:Application> or other top-level component tag.

Statements and expressions are allowed only if they are wrapped in a function. In addition, you cannot define new classes or interfaces in <fx:Script> blocks. Instead, you must place new classes or interfaces in separate AS files and import them.

All ActionScript in the block is added to the enclosing file’s class when Flex compiles the application. The following example declares a variable and sets the value of that variable inside a function:

<?xml version="1.0"?>
<!-- usingas/StatementSyntax.mxml -->
<s:Application 
    xmlns:fx="http://ns.adobe.com/mxml/2009"    
    xmlns:mx="library://ns.adobe.com/flex/mx"     
    xmlns:s="library://ns.adobe.com/flex/spark"
    creationComplete="doSomething()">

    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout>
    
    <fx:Script>
        <![CDATA[
        public var s:Boolean;
        
        public function doSomething():void {
            // The following statements must be inside a function. 
            s = label1.visible; 
            label1.text = "label1.visible = " + String(s);
        }
        ]]>
    </fx:Script>
    
    <s:Label id="label1"/>
    
</s:Application>

The executing SWF file for the previous example is shown below:

Most ActionScript statements must be inside functions in an <fx:Script> block. However, the following statements can be outside functions:

  • import

  • var

  • include

  • const

  • namespace

  • use namespace

When using an <fx:Script> block, you should 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. Adobe recommends that you write all your <fx:Script> open and close tags as the following example shows:

<fx:Script> 
    <![CDATA[ 
        ... 
    ]]> 
</fx:Script>

Flex does not parse text in a CDATA construct, which means that you can use XML-parsed characters such as angle brackets (< and >) and ampersand (&). For example, the following script that includes a greater-than (>) comparison must be in a CDATA construct:

<?xml version="1.0"?>
<!-- usingas/UsingCDATA.mxml -->
<s:Application 
    xmlns:fx="http://ns.adobe.com/mxml/2009"    
    xmlns:mx="library://ns.adobe.com/flex/mx"     
    xmlns:s="library://ns.adobe.com/flex/spark"
    creationComplete="doSomething()">

    <s:layout> 
        <s:VerticalLayout/> 
    </s:layout>

    <fx:Script>
        <![CDATA[
        public var m:Number;
        public var n:Number;
        
        public function doSomething():void {
            n = 40;
            m = 42;
            label1.text = "40 < 42 = " + String(n < m);
        }
        ]]>
    </fx:Script>
    
    <s:Label id="label1"/>
    
</s:Application>

The executing SWF file for the previous example is shown below:

Accessing ActionScript documentation

The ActionScript 3.0 programming language can be used from within several development environments, including Adobe® Flash® Professional and Adobe® Flash® Builder™.

The Flex documentation includes ActionScript 3.0 Developer's Guide, which describes the ActionScript language. The ActionScript API reference is included as part of the ActionScript 3.0 Reference for the Adobe Flash Platform.