Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

📄 Contents

  1. Attaching Button Events in Flex
  2. Creating Custom Functions in Flex
  3. Whats Next?
  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Creating Custom Functions in Flex

To start separating your code into functions and removing it from the buttons, you’ll need to create Script tags in your MXML. When you create a Script tag, Flex will automatically add CDATA to it. Remember, MXML is essentially XML, so as with all XML files, CDATA is necessary when adding special characters to your file.

Listing 3 MXML Script Tags

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
     <![CDATA[
     ]]>
     </mx:Script>
     <mx:Button label="My Button" click="recordEvent(’Click’);" mouseUp="recordEvent(’Up’);" />
</mx:Application>

Once the Script tags are in place, we can import the Alert class and begin to create our function. The sample function we are creating is called recordEvent and it takes a String as a parameter named event. All ActionScript is strongly typed in Flex, so we’ll also add the public keyword to the function. Within the function we’ll add the same Alert code from the previous example, but this time we’ll pass it the String event parameter.

Listing 4 Adding a Function

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
      <![CDATA[
      import mx.controls.Alert;
      public function recordEvent(event:String):void
     {
       Alert.show(event);
     }
     ]]>
     </mx:Script>
     <mx:Button label="My Button" id="myButton" click="recordEvent(’Click’);" mouseUp="recordEvent(’Up’);" />
</mx:Application>
  • + Share This
  • 🔖 Save To Your Account