The Script Element, Adding An Action To A Button And Functions In Flex

5th November 2008 - 3 minutes read time

Yesterday I talked about creating some simple Flex elements in your application. Today I will introduce a new element called Script.

The Script element, if you haven't already guessed is used to run your application function and should be contained within the Application element. You can either put script inline like this.

  1. <mx:Script>
  2. // some code here
  3. </mx:Script>

Or you can use the source attribute and link it with an external ActionScript source file.

  1. <mx:Script source="">
  2. </mx:Script>

The simplest thing you can do is use the function trace(). This is a debugging function that will output information into the debugging Window in your Flex IDE. To print out a message when your application is first run do the following.

  1. <mx:Script>
  2. trace('Flex program running.');
  3. </mx:Script>

To capture a mouse click on a Button element you need to use the attribute click, the value of which can be either come code or a callback to a function. To use inline code using the following, which will print out a trace.

<mx:Button id="abutton" label="A button" click="trace('Button clicked');" />

To use a callback function do the following.

<mx:Button id="abutton" label="A button" click="clicked();" />

In your script section you can now add the function that you want, and perhaps do more than just a simple trace() call. The following script will send a trace message to your output and then open a browser window to the #! code site. If you embed this application within a web page then the current browser window will redirect to the URL.

  1. <mx:Script>
  2. public function clicked():void
  3. {
  4. trace('Button clicked');
  5. navigateToURL(new URLRequest(''));
  6. }
  7. </mx:Script>

To create a function you need to use the following syntax:

  1. scope function functionName():return type
  2. {
  3. }

The scope is how the application will see the function. For a function like this that is outside the scope of a class (which is another topic) it should have public scope. The return type is the type of value that is returned by the function, and if no value is to be returned then void is used. If the function adds two numbers together and returns the result then the return type would be Number.

Add new comment

The content of this field is kept private and will not be shown publicly.