I’ve been using Flash since version 4 and think that I know most of the intricacies and workarounds in the application. I also consider myself an expert with XML and ActionScript, but when I tried to make the transition to Flex for the first time I was completely lost. The good news is that it’s really quite simple once you understand it. If you’re a developer, it’s even easier than using Flash because it provides accurate error checking and much more coding power.
The Flash to Flex series will focus on helping you migrate your work environment from Flash to Flex by learning the differences between and comparing the two applications. In this article, you’ll learn how to get started integrating ActionScript with MXML by attaching code on a simple button click and including custom functions in your Flex project.
Attaching Button Events in Flex
After you create a Flex project, you’ll begin with a new MXML file. At first, this file might look foreign, but don’t be intimidated—essentially it’s just XML.
Adding buttons to your file is quite different in Flex, depending on how you approach it, because there are actually two different views in Flex: Design and Source, much like in Dreamweaver. Instead of drawing an object and then converting it into a symbol, as was done in Flash, you can simply use Flex’s Design view to drag and drop components to the stage, such as buttons, accordions, and much more.
When dragging a button to the stage in Design view, Flex creates the Source of the button for you in the MXML file. But if you like to work with the code, you can use the Source view to write your own, and the Design will be created for you as well. So, it goes both ways, you create Source, Flex creates Design; you create Design, Flex creates Source. For the rest of this article I will be focusing on the Source view.
After you add a button to your file, you’ll have code that looks similar to Listing 1:
Listing 1 Source View of a Flex Button
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Button label="My Button" /> </mx:Application>
After we have the button, Flex offers us all its properties and events through code hinting. The label property that I added to the button is used to add text to it (a good example of this is a submit button for a form).
Listing 2 Source View of a Flex Button with Events
<?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; ]]> </mx:Script> <mx:Button label="My Button" id="myButton" click="Alert.show(’Click’);" mouseUp="Alert.show(’Up’);" /> </mx:Application>
I know, this is a pretty annoying example, but it really shows you how to attach the events to buttons in Flex.