Home / Articles / Adobe Flash / From Flash to Flex: Integrating ActionScript with MXML

From Flash to Flex: Integrating ActionScript with MXML

Contents

  1. Attaching Button Events in Flex
  2. Creating Custom Functions in Flex
  3. Whats Next?

Article Description

Are you familiar with Flash and interested in making a move to Flex? This article is for you. It will show you the differences between the two applications and how to make a smooth transition. In this first article of a multipart series, "From Flash to Flex," Kris Hadlock shows you how to begin creating your first Flex application by integrating ActionScript with MXML.

Like this article? We recommend

Adobe Flex 2: Training from the Source

Adobe Flex 2: Training from the Source

$54.99

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>
3. Whats Next? | Next Section Previous Section