- Creating a Package
- Using a Custom Class
- Next in the Series
Using a Custom Class
In the last article, "Integrating ActionScript with MXML," I showed how to create a simple method called recordEvent, which used the Alert class for notification of a few mouse events. In this article I will take that same method, add it to the new custom Alert class that we created, and show you how to use it in a project.
First, take a look at Listing 4 to see how to add the recordEvent method to our class.
Listing 4 Creating a custom method in the Alert class
package com.studiosedition.utilities { public class Alert { public static function RecordEvent(event:String):void { mx.controls.Alert.show(event); } } }
You should notice a couple of interesting facts about the RecordEvent method. The first letter of the method name is now capitalized. I do this to differentiate methods in my classes, I prefer to code public methods this way and have private methods starting with lowercase (this is sort of a standard coding practice, but not a requirement).
The next thing to notice is the static keyword, which I added to allow the method to be called without class instantiation. This means that you can simply call Alert.RecordEvent()instead of creating a new Alert object before calling the method.
With our new method in place, let’s start calling it from the MXML file that is created when a project is started. Listing 5 shows how to import our new Alert class and use a button to trigger the RecordEvent method.
Listing 5 Incorporating AS 3 with MXML
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script><![CDATA[import com.studiosedition.utilities.Alert;]]></mx:Script> <mx:Button label="My Button" id="myButton" click="Alert.RecordEvent(’Click’);" mouseUp="Alert.RecordEvent(’Up’);" /> </mx:Application>
The first things you’ll notice are the Script tags, with the import statement for our new custom Alert class, which enables us to have access to the code that we wrote previously. With the class imported, we can call the public methods contained within. As an example I created a button with a label, id, and two events. The events are tied to the RecordEvent method to notify when either the click or mouseup event is fired.
That’s it. I know this is a simple example, but the concepts are the same no matter how complex your code gets.