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 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, Macromedia 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.macromedia.com/2003/mxml">

<mx:Script>
   <![CDATA[
      var z:Number;

      function doSomething() {
         z = z + 1;   // This must be in a function.
      }
   ]]>
</mx:Script>
...
</mx:Application>

Version 1.5

 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flex/15/flex_docs_en/00000048.htm