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.
// some code here
Or you can use the source attribute and link it with an external ActionScript source file.
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.
trace('Flex program running.');
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.
public function clicked():void
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.