Learning Flex 3 - Adding Interactivity with ActionScript, Part 2

August 11, 2008 |
AddThis Social Bookmark Button
Pages: 1, 2, 3

Making Things Happen

Returning to the HelloWorld application, you’ll now make some things happen.

First, you’ll add a few more sources of user input. You have a name field already, so now you’ll add an age field. Place another Label with the text “My age is:” below the name text input, place a NumericStepper control below that, and give them the id attributes ageLabel and ageNS. The NumericStepper control is like a TextInput control that accepts only numbers and has special keyboard and mouse interactions to make increasing or decreasing the numbers easy. You’ll want to set a couple of properties on the NumericStepper to customize it. The property maximum will set the top value allowed, and the minimum property will set the minimum. Set these to a maximum of 120 and a minimum of 18. This additional code should look like the following:

                    
<mx:Label id="ageLabel" text="My age is:"/>

<mx:NumericStepper id="ageNS" maximum="120" minimum="18" />

Using Pop-up Alerts to Display Information

Now that you have a basic form, you’ll display the data in a pop-up. To do that, you’ll create a function that uses the class called Alert, which is used to display pop-up alerts:

                    
                    import mx.controls.Alert;

public function showInfo():void

{
 
 Alert.show("Your name is " + fullNameTextInput.text + 
 
 " and your age is " + ageNS.value);
 
}

Notice the import statement that imports the Alert class necessary for this function. Remember that when you use code completion, most imports will be written for you automatically.

This function has a few features you haven’t learned about yet. One is the show() method on the Alert class. This is a static method, one that exists on the Alert class itself, that displays a window centered above everything else.

Static Properties and Methods

Take a look at the code for displaying an alert, and notice the show() method. This has a different syntax than you may be accustomed to using, because it exists on the Alert class instead of an instance of that class. That is to say, you’re using the class name (Alert), and calling the method using dot notation on the Alert class.

Just like constants, which are properties that are attached to a class, static methods are attached to a class. Instead of creating a variable of Alert type, (such a calling new Alert()), and then calling the show() method on that instance, you call the method on the Alert itself.

Constants are generally static properties of a class, meaning they are variables attached to the class itself, and that is why you use a similar syntax for constants and static methods. (These are actually created using the static access modifier when creating such methods or variables in ActionScript.)

Also note the value property of the NumericStepper control. Because the value property behaves similarly to a TextInput control, you might expect the property you’re looking for is text. However, the NumericStepper actually holds numeric data, so its property is called value instead. Because it is a Number, you can do math calculations with its value property, like
ageNS.value + 10 to add 10 years to your age. (On second thought, maybe taking away 10 years from the age would be better.)

This addition calculation brings up another point. Plus signs (+) are used in ActionScript to both add numbers and piece together text. The use of the plus signs in the case of adding years to your age would be addition, but in the case of the " and your age is " + ageNS.value, the plus sign is used for concatenation, or the linking together of data. What you’re doing in your application is creating a phrase that has dynamic information gathered from your form fields. Although the value property, as you just learned, is numeric, Flex is smart enough to realize that it can’t add a number to a string of text such as " and your age is " so it changes the numeric value into a text value for you. This might not even be something you would’ve noticed, but it’s good to recognize, because this functionality may not work as expected in all situations. See the box “Conversion, Coercion, and Casting” for more information.

Conversion, Coercion, and Casting

So, now you understand the idea of typing your variables. You’ve thought it out and decided what types your variables should be, you’ve typed everything nicely, and you feel confident that your code is clean and optimized. Then you wake up one morning and realize you need to change one data type into another. What to do?

A few methods of conversion are available to you, the Flex and ActionScript guru that you are. One is coercion, or implicit conversion. This happens when you have a variable of a numeric type but you imply in your code that this number should be displayed as a string. Such is the case when setting a TextInput’s text property to a number. In some cases, this will be fixed for you automatically, but sometimes the compiler will complain. Then you need to do an explicit conversion, also known as casting or typecasting. This kind of casting means you want to tell the compiler to convert, at least temporarily, the type of a value to another type. In the case of using a number in the text property, you want to change a numeric value to a text value.

You have lots of ways to accomplish an implicit conversion at your disposal. One way is to use the constructor of the desired type to convert the value. The constructor is the special method used to create a new instance of a class, such as new String(). It’s the method of the same name as the class. Using the constructor and passing in a value will convert the value. For instance, you could use the code fullNameTextInput.text = String(ageNS.value). An additional means of casting is using the keyword as. This tells the compiler to think of a value in another way. Use the code fullNameTextInput.text = ageNS.value as String to do that. A final means of conversion is to use the toString() method, which most classes in Flex have implemented. The toString() method returns a string representation and is a useful method to know. In that case, you could use the code fullNameTextInput.text = ageNS.value.toString().

One last thing to notice in the example is the way the code breaks across two lines, even though it’s considered one entity. Usually you’ll need to put everything that is a complete statement on one line, such as passing a long parameter into the show() method. But, when you have plus signs or commas, you’re allowed to bend the rules and break the line. For readability, you place an indentation in front of the following line to show that it is a continuation of the previous line. Of course, you could still place all this code on one line, but that may make it difficult to read for some users with smaller screens, causing them to have to scroll horizontally to read all the code.

Note: A good rule of thumb is to set a maximum line length of 80 characters of text in your source code. That way it will be readable to most people.

0604 Figure
Figure 6-4. An Alert displaying some information

The next step is to remove the previous setForm() function you created and to register the button’s click event with your new showInfo() function so that when a user clicks the button, a pop-up alert displays. Do that, and then go ahead and run it to see your work. You should see an alert similar to the one in Figure 6-4. The full code for your application so far may look like this:

                    
<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" 

applicationComplete="fullNameTextInput.setFocus()">

<mx:Script>



import mx.controls.Alert;

public function showInfo():void

{
 
 Alert.show("Your name is " + fullNameTextInput.text + 
 
 " and your age is " + ageNS.value);
 
}



</mx:Script>

<mx:Panel id="panel" x="10" y="10" width="250" height="200" 

layout="vertical" title="Howdy Ya'll" paddingLeft="5">

<mx:Label text="My name is:" fontWeight="bold"/>

<mx:TextInput id="fullNameTextInput"/>

<mx:Label id="ageLabel" text="My age is:" fontWeight="bold"/>

<mx:NumericStepper id="ageNS" maximum="120" minimum="18" />

<mx:CheckBox id="expertCheckBox" label="I'm a Flex Expert!"/>

<mx:Button label="Click me" click="showInfo()"/>

</mx:Panel>

</mx:Application>

Using Change Events

So far you’ve worked only with click events, which occur when a Button or other control is clicked. Now you’ll learn how to deal with another type of event, a change event. These often occur when a selection changes or a text or value changes on a control. When a NumericStepper or TextInput changes, the controls fire change events. So, add a listener for the change event on your NumericStepper control that runs the showInfo() function:

                    
<mx:NumericStepper id="ageNS" maximum="120" minimum="18" change="showInfo()" />

Now, when the value of the NumericStepper changes, this event fires, and you’ll see the pop-up alert. The change will occur when either using the mouse to change the value via the arrow buttons, using up and down arrows on the keyboard, or typing in the NumericStepper and then confirming the change (by pressing the Tab key or using the mouse to select another component). Notice that both a Button’s click event and this NumericStepper’s change event are registered with the same showInfo() function. It’s totally fine to do that. Registering multiple functions to listen to one event is part of the power of programming.

What Flex Does When You’re Not Looking

You might be wondering at this point how Flex does what it does. You write some MXML or create your masterpiece in Design mode, but what happens when you push that little green button?

Flex is, in one respect, a compiler for MXML and ActionScript. When using Flex Builder to compile your application, a script runs in the background that does the following:

  1. Converts all MXML into ActionScript
  2. Converts all metadata into compiler arguments
  3. Compiles the generated ActionScript into bytecode (.swf file)

ActionScript is still the main language for Flash applications. MXML is great for easily creating applications and has great options like styling and creating services and effects. But the Flex compiler converts your MXML into a web of ActionScript classes, essentially taking your high-level code and creating lots of lower-level code. All this code gets recompiled into SWF bytecode, which is a set of instructions for Flash Player. It also looks at special metadata (the stuff in square brackets) and injects that into the SWF as well; things like embedded assets, settings for frame rates, and so on.

Pages: 1, 2, 3

Read more from Alaric Cole. Alaric Cole's Atom feed

Tag Cloud

iPad

What's your take on the iPad? (Putting aside the Flash/iPad flame war)

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.