Chapter 4. ActionScript

ActionScript is the programming language that you can use along with MXML to create sophisticated Flex applications. Although MXML is an important part of a Flex application, it is mostly used for creating the user interface, and it can go only so far in creating a complete application. For data models and sophisticated client-side business logic, you’ll need to use ActionScript as well.

Flex applications require ActionScript 3.0, which represents a significant maturation from earlier versions of the language. ActionScript 3.0 is compliant with the ECMA-262 specification and leverages parts of the pending ECMAScript Edition 4 specification. ActionScript 3.0 supports a wide range of features, including formalized classes, interfaces, packages, runtime exception handling, runtime data types, reflection, regular expressions, E4X (XML), and more.

ActionScript is a standards-based, object-oriented language. Because ActionScript is an object-oriented language, it can be viewed as a collection of APIs generally in the form of classes. There are three tiers of ActionScript APIs:

Flash Player APIs

These APIs are part of the Flash Player itself, and they run natively in that runtime environment. Flash Player APIs consist of core classes such as String, Number, Date, and Array as well as Flash Player-specific classes such as DisplayObject, URLLoader, NetConnection, Video, and Sound.

Flex framework APIs

These are the APIs that make up the Flex framework itself. The Flex framework is written in ActionScript, so it leverages the lower-level Flash Player APIs. The Flex framework is effectively a layer on top of the Flash Player APIs. The Flex framework APIs consist of all the Flex containers (Application, VBox, etc.), controls (Button, TextInput, etc.), and other assorted data, manager, and utility classes that are discussed throughout much of this book.

Custom APIs

These APIs are for the classes you build for use in custom applications. Custom classes can use Flash Player APIs as well as the Flex framework APIs.

The APIs that are intrinsic to Flash Player are far too large a category to attempt to discuss in this chapter, and in fact there are books spanning many hundreds of pages that still can’t cover all of the Flash Player APIs. Our assumption in this book is that either you're already basically familiar with the Flash Player APIs or you're also reading a companion reference specific to Flash Player APIs. Most ActionScript 3.0 books focus primarily on the Flash Player APIs. You will most likely find that the Flex documentation API reference is quite helpful in this regard.

Note

Much of this book is dedicated to the Flex framework APIs, via either ActionScript or MXML. For that reason, this chapter doesn’t focus on the Flex framework APIs. ActionScript 3.0 is an object-oriented language, which means that in one form or another, the ActionScript code you write is part of a class. This book assumes you're already familiar with basic object-oriented programming concepts. It's not our intention to attempt to teach object-oriented theory in this chapter. Yet you will need to have a fundamental understanding of object-oriented concepts to make the most of this chapter.

ActionScript is an important and essential part of Flex applications. In fact, ActionScript is the foundation upon which the entire Flex framework is written. This chapter teaches you the important fundamental concepts about ActionScript, including the relationship between MXML and ActionScript, ActionScript syntax, events, error handling, XML, and reflection.

Using ActionScript

When you want to use ActionScript within Flex, you have four basic options for where to place the code:

  • Inline within MXML tags

  • Nested within MXML tags

  • In MXML scripts

  • Within ActionScript classes

The preceding lists the techniques for working with ActionScript code, from the simplest to the most complex form. We’ll look at each of these techniques in the following sections.

Inline ActionScript

Inline ActionScript appears within MXML tags. Believe it or not, you’ve already seen several examples of this in Chapter 3. Inline event handling and data binding using curly brace syntax necessarily uses basic ActionScript. The following example uses ActionScript to display an alert dialog box when the user clicks on a button:

<mx:Button id="alertButton" label="Show Alert"
           click=" Alert.show('Example')" />

In this example, the text assigned to the click event handler attribute is ActionScript code, which calls a show() method of an ActionScript class called Alert.

Note

The preceding example shows how to open an Alert component from a button. The code is a snippet and is not provided in the context of a complete MXML document. The Alert component is in the mx.controls package, and to use the component you must add an import statement to the document. If you're using Flex Builder, it automatically adds the import statement for you. Otherwise, you’ll need to add a Script tag with the import statement.

The next example uses data binding syntax (curly braces) to indicate that the ActionScript expression contained within it should be evaluated at runtime:

<mx:VBox>
  <mx:TextInput id="input" />
  <mx:Text id="output" text="{input.text}" />
</mx:VBox>

This example uses the ActionScript expression input.text. The input object referenced is the text input control with an ID of input. At runtime, this expression is evaluated and then assigned to the text property of a Text component.

Inline data binding represents the most limited use of ActionScript, because it can evaluate only one expression. For instance, the preceding example evaluates the expression input.text. You could use a more complex expression, such as the following:

<mx:VBox>
  <mx:TextInput id="input" />
  <mx:Text id="output" text="{'User input: ' + input.text}" />
</mx:VBox>

This example concatenates the string User input: with the user input from the text input control. You can also create even more complex expressions using inline data binding.

Inline event handlers allow you to write more complex ActionScript that can consist of several statements. ActionScript statements generally end with semicolons. The following example illustrates a button with slightly more complex event handler code, consisting of two expressions:

<mx:Button id="alertButton" label="Show Alert" click="Alert.
show('Example');alertButton.x += 40;" />

Note

The preceding example and subsequent examples will show the button moving only if placed in a container using canvas layout rules. If you test this code inside an Application container, make sure the container’s layout style is absolute.

This example first displays an alert dialog box. It then moves the button to the right by 40 pixels. Although you can string together many statements (as in this example), it is very uncommon. It’s not difficult to understand why this would be. Rather simply: the code is difficult to read and manage when you try to use several inline statements in that fashion. If an event handler needs to run several statements, it is far more common to simply call a function. We’ll look at functions in more detail in the next section, and then later in the chapter, in the Methodsˮ section.

Nested ActionScript

You also can nest ActionScript code within MXML tags. Just as you can nest values for most properties, you can nest the values (ActionScript) for event handlers. You must place the code within a CDATA block. Here’s an example:

<mx:Button id="alertButton" label="Show Alert">
  <mx:click>
    <![CDATA[
      Alert.show("Example");
    ]]>
  </mx:click>
</mx:Button>

Nesting code in CDATA blocks within tags in this fashion looks much better than trying to cram a bunch of code inline within a tag. This might give you the idea that you should place large blocks of code nested within a tag in this fashion:

<mx:Button id="alertButton" label="Show Alert">
  <mx:click>
    <![CDATA[
      Alert.show("Example");
      alertButton.x += 40;
      alertButton.y += 20;
    ]]>
  </mx:click>
</mx:Button>

Although this certainly is more readable than a block of inline code, it is not the recommended way to use blocks of code with components. Instead, it is far better to centralize your code blocks within functions in MXML scripts or in classes. You can then limit ActionScript on components to one line of code.

MXML Scripts

The second way to add ActionScript code to an application is to place the code within an MXML script. An MXML script appears in an MXML document within a Script element:

<mx:Script>
</mx:Script>

Because ActionScript code may use special characters otherwise interpreted by the MXML compiler, you must place ActionScript code within Script tags and also within a CDATA block, as in the following example:

<mx:Script>
<![CDATA[

  import mx.controls.Alert;

  private function alertButtonClickHandler():void {
    Alert.show("Example");
    alertButton.x += 40;
    alertButton.y += 20;
  }

]]>
</mx:Script>

By placing code in functions within Script tags, you can limit the amount of code you need to place on component tags. For example, using the preceding script block, you could simplify the code on a button component as follows:

<mx:Button id="alertButton" label="Show Alert" click="alertButtonClickHandler();" />

You can optionally place ActionScript code blocks in separate files, and you can embed them in a script block using the source attribute of a Script tag:

<mx:Script source="code.as" />

Note

Unlike class files (which are discussed in the next section), ActionScript files such as code.as from the preceding example do not require special syntax. Instead, you can think of an external ActionScript file included via the source attribute of a Script tag as nothing more than a way to move the code from the MXML file to an external file. At compile time, the code from the external ActionScript file gets inserted inside the Script tag. If you're using Flex Builder, you can create new ActionScript files by selecting File→New→ActionScript File.

Within MXML scripts, you can import classes and declare properties and methods. We discuss each of these in more detail in Understanding ActionScript Syntaxˮ later in this chapter.

Classes

Classes are the most sophisticated and powerful use of ActionScript. Although it’s not wrong to use inline code and MXML scripts, it’s generally advisable to have a bias for placing ActionScript code within ActionScript classes.

ActionScript class code exists within separate files apart from the MXML application and component documents. ActionScript class files are text files that use the file extension .as. We’ll talk more about creating classes later in this chapter, in Declaring Classes.”

Get Programming Flex 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.