Learning Flex3 Task 3: Using function in script tag and in separate ActionScript file
Posted on | June 7, 2008 |
In the last example we have used some functionality against the click event of the button. Now we will encapsulate the code in a function and call it.
For embedding script we have to use a special tag in flex. It is the mx:Script tag. Inside the tag we will use a CDATA section to write the script codes. If any of us is not aware of what CDATA is, just to inform him/her inside CDATA no tag is parsed. You can write virtually whatever you like.
Let’s add a script tag into our application.
<mx:Script>
<![CDATA[
public function clearText():void
{
lblName.text = '';
txtName.text = '';
}
]]>
</mx:Script>
Calling this function is simple as you might guess:
<mx:Button id=”btn1″ label=”Clear All” click=”clearText()” />
Don’t forget to enter some comments, it’s a good practice.
The entire code will now look like:
<?xml version=”1.0″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml”>
<mx:Script>
<![CDATA[
/**
* clear text clears the text of the text and the label
* it is invoked from Button btn1;
*/
public function clearText():void
{
lblName.text = '';
txtName.text = '';
}
]]>
</mx:Script>
<mx:Panel title=”App 2″>
<mx:TextInput id=”txtName” text=”hello” />
<mx:Button id=”btn1″ label=”Clear All” click=”clearText()” />
<mx:Label id=”lblName” text=”{txtName.text}”/>
</mx:Panel>
</mx:Application>
But it’s not a good idea to write down logic and layout in the same file. Just like we use separate js files for JavaScript codes with html, we can also use a separate ActionScript file for the code and put the layout code in the mxml file.
Here I have created a file and pasted the function code into it. Saved the file as app2.as in the same folder of the main.mxml file. You can use any valid names for the ActionScript file with the extension .as since it is the default extension for ActionScript files.
We can now use this file as the source of the script in this way using the source attribute:
<mx:Script source=”app2.as” />
Prev: Learning FLex3 Task2 : First action and accessing component property
Start: Learning Flex3 Task1: IDE and basic application
Next:
Comments
Leave a Reply