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

Wednesday, November 5, 2008 - 11:18

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
2
3
<mx:Script>
// some code here
</mx:Script>

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

1
2
<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.

1
2
3
<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.

1
2
3
4
5
6
7
<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:

1
2
3
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.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment