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

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.

<mx:Script>
// some code here
</mx:Script>

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

<mx:Script source="myactionscriptfile.as">
</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.

<mx:Script>
trace('Flex program running.');
</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.

<mx:Script>
public function clicked():void
{
 trace('Button clicked');
 navigateToURL(new URLRequest('http://www.hashbangcode.com'));
}
</mx:Script>

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

scope function functionName():return type
{
}

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.
CAPTCHA
5 + 13 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.