User Guide

Using ActionScript in Flex applications 47
Flex does not parse text in a CDATA construct so that you can use XML-parsed characters such as
angle brackets (< and >) and ampersand (&). For example, the following script that includes a less
than (<) comparison must be in a CDATA construct:
<mx:Script>
<![CDATA[
function changeText() {
var x:Number = 1;
if (x<3) {
ta1.text = "Hello world";
}
}
]]>
</mx:Script>
Referring to Flex components
When you refer to Flex components in ActionScript, the component must have an
id property
set. You then use the
id to refer to that component.
For example, you can define a TextArea control in MXML using the
<mx:TextArea> tag, as the
following example shows.
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" >
<mx:TextArea id="ta1" text="Congratulations. You are a winner." />
</mx:Application>
To access that components methods or properties, use dot syntax. The following example gets the
value of the TextArea named ta1:
var str:String = ta1.text;
You can refer to the current enclosing document or current object using the this keyword. For
more information, see Chapter 16, “Working with ActionScript in Flex,” in Developing Flex
Applications.
Using ActionScript blocks in MXML files
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 files 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, Macromedia recommends that you write all
your
<mx:Script> open and close tags as the following example shows:
<mx:Script>
<![CDATA[
...
]]>
</mx:Script>