Getting Started with External Class Files


As mentioned earlier, custom class construction is nothing new, but the manner in which it is done is completely new to anything we have gone over so far. In older versions of Flash, you could create classes of objects either externally or internally in the Flash file. But with the introduction of ActionScript 2.0, the only way to correctly build object classes is externally in .as files.

Here are two examples of building the same class, one in ActionScript 1.0 and the other in ActionScript 2.0.

Here's how you would do it in ActionScript 1.0:

 function Bird (){     //create an event     this.onLand=function(){};     //create a fly method     this.fly=function(speed, distance){         //fly     }     //create a method to check altitude     this.checkAltitude=function(){         if(this.altitude <= 0){             //call the event for when the bird lands             onLand();         }         return this.altitude     } } 

And this is what you would do in ActionScript 2.0:

 //get the ability to use listeners import mx.events.EventDispatcher; class Bird{ //declare the methods and properties     public var altitude:Number;     public var addEventListener:Function;     public var removeEventListener:Function;     private var dispatchEvent:Function; //initialize the ability to have listeners     function Bird(){         EventDispatcher.initialize(this);     }     //create a fly method     function fly(speed:Number, distance:Number):Void{         //fly     }     //create a method to check altitude     function checkAltitude():Number{         if(this.altitude <= 0){             //trigger the listener             dispatchEvent({type:"onLand"});         }         return this.altitude;     } } 

You can definitely see the difference in complexity in the ActionScript 2.0 version compared to the ActionScript 1.0 version, but with that complexity comes much more power, flexibility, and scalability than ever before. Don't worry if you do not understand everything in the preceding code; as we move through the chapter, each part will be covered.

Defining a Class

The concept of object-oriented programming was covered back in Chapter 8, "Welcome to ActionScript 2.0," so there is no need to repeat that information here. When creating a class, you are defining what the class has in it, what it can do, and what events are taking place.

Defining a class in ActionScript 2.0 is as simple as using the keyword class, the name of the class, and opening and closing curly brackets like this:

 class MyClass{     //class instructions } 

Of course this class does not do anything, nor does it have any properties, but we will get to that soon enough.

And when defining a class, you do not always have to start from scratch. If there is a class already made you want to use as a base for your class, you can extend that class with a subclass (child class), like this:

 class Shape extends MovieClip{     //extends the MovieClip class } 

Now the new class Shape extends the MovieClip class, and therefore has all of the MovieClip properties and methods plus whatever is created within the Shape class itself.

NOTE

Notice that all of the classes we have built thus far are capitalized. This is not necessary, but it is good coding practice to capitalize class names for easy readability. And remember, ActionScript 2.0 is case sensitive, so when you create instances of the new object, use the same case.


NOTE

Another thing of note when building external classes is that the filename must match the class name. For instance, if you have a class called Bird, it must reside in a file named Bird.as.


That covered how to build a class, but so far our classes do not have anything in them. Let's start placing methods and properties in them.

Public, Private, and Static

Before we start creating properties and methods, it's important to know a few keywords that describe how these properties and methods interact in Flash.

When you declare properties and methods, you can use the keywords public or private to set boundaries for their use.

Public means that they can be used within the class itself, or in conjunction with an instance of the object in Flash.

Private means that the property or method can only be used internally in the object class itself.

Here are a few small examples of public and private:

 class Bird{     public var birdType:String;     public var weight:Number;     private var feathers:Number;     public function fly (speed:Number, distance:Number):Void{         //fly     }     private function featherCount():Number{         return this.feathers;     }     public function molt():Void{         this.feathers = this.featherCount()-25;     } } 

You can see that we create two public properties and one private property for the Bird class of object. We then create a public method to allow the bird to fly. After that, we create a private method that can only be used in this class file. Then we use the private method from within a public method to remove some of the bird's feathers.

The benefit of using public and private is that sometimes in object classes, you don't want certain properties or methods to be accessible directly from the a Flash file: Instead, they are called from within other methods, properties, or events. If you do not declare whether a method or property is either public or private, it will be public by default.

There is another keyword that can be used when creating properties or methods with object classes: the static keyword. Making a property static means that it can only be accessed by using the object's class name, not an instance of that object. Static methods and properties are not new to Flash; in fact, here are a few examples using them with the Math object:

  • Math.PI Approximately 3.1415926

  • Math.E Approximately 2.71828

  • Math.tan(0) Returns tangent of number 0

Notice that when we call either a property or method of the Math object, we use the class name, not an instance of the object.

Most static methods and properties are used with object classes that have just static methods or properties, and they rarely have events. Classes with static elements are used to perform certain tasks where instances of that object class would not be necessary, such as the Math class.

And when creating static properties or methods of objects, they can be either private or public like the following code, which would appear within a class:

 private static var age:Number = 23; public static function square(num:Number){     return num*num; } 

Those are the keywords that will help define properties and methods in external ActionScript files.

Declaring Properties with a Constructor Function

Sometimes when you create an instance of an object, you want to set some of the properties of that object right when it is being created. To do so, you need a constructor function inside the class definition.

A constructor function uses the class's name as the function name within itself, so when an instance of that object is created, everything within the constructor function will be done.

Here is an example of using a constructor function to build a House object:

 class House{     //declare some properties     public var houseWidth:Number;     public var houseHeight:Number;     public var stories:Number;     public var houseType:String; //create the constructor function     function House(width,height,stories,houseType){         this.houseWidth = width;         this.houseHeight = height;         this.stories = stories;         this.houseType = houseType;     } } 

And you can then create an instance of the House object in Flash like this:

 var homeSweetHome:House = new House(50,50,2,"rancher"); 

Now you see not only how to create properties, but also how to create them when an instance of the object is created. Next is how to declare methods.

Creating Methods

If properties are information about an object, methods are what objects do. A method is nothing more than a function directly associated with an object.

When creating a function, it is important to remember to declare whether it is private or public. Otherwise, it will automatically become public, which may not be what you want. It is good practice to always declare which type of method it is no matter which type it will be.

Also note that you cannot declare a blank function and then define it later in the code. Here is an example that will cause an error trying to accomplish this:

 class Bird{     public var fly:Function;          function fly(){         //fly     } } 

If you attempt to use this code, an error will occur saying that the function cannot be created twice; just something to keep in mind.

Also, when you declare a function, you can set the type of data to be returned. Here is an example of that:

 class Bird{     private var altitude:Number;     public function getAltitude():Number{         return this.altitude;     } } 

As you can see, in the preceding example, the method getAltitude() will return the current altitude of any instance of the Bird object, and it will always be a number.

But if you are creating a method that will not return a value, you can declare that as well, as you can see in this next example:

    class Bird{    private var altitude:Number;    private function increaseAltitude(amount:Number):Void{        this.altitude += amount;    } } 

Notice that we used the keyword Void instead of a data type to declare that this method will not return any data. If a method with the Void return type attempts to return data, an error message will appear.

There are also two types of methods that are unique and can be created within external AS files.

Creating Getter/Setter Methods

Getter and setter methods are unique among other methods created in object classes because when they are accessed, they are not accessed in the same way most other methods are. When methods are called, they have a set of parentheses following the name of the method; this is how you can distinguish methods. Getter/setter methods are created in much the same way other methods are created, but they are accessed like properties.

The reason behind this is that it is bad practice for a user to directly access a property of an object, so developers often create methods to both get the information from a property and set information to that property. But getter/setter methods alleviate this problem by creating methods that can be accessed like properties.

Here is an example of creating a getter method using the keyword get:

 class Bird{     //declare a property     private var birdWeight:Number;     //create the constructor function     function Bird(weight){         this.birdWeight = weight;     }     //create the getter method     public function get weight():Number{         return birdWeight;     } } 

And here is the code that will create a new instance of the Bird object and then get the weight. The code is in a Flash file that resides in the same directory as the Bird.as file:

 //create a new Bird with a weight of 40 var myBird:Bird = new Bird(40); //get the birds weight trace(myBird.weight); 

As you can see if you test this code, the weight of the bird is returned because we called the getter method, but it looks like a property, not a method.

Here is an example, extending the preceding example to now include a setter method:

 class Bird{     //declare a property     private var birdWeight:Number;     //create the constructor function     function Bird(weight){         this.birdWeight = weight;     }     //create the getter method     public function get weight():Number{         return birdWeight;     }     //create the setter method     public function set weight(amount:Number):Void{         this.birdWeight = amount;     } } 

And here is the update to the Flash code that will create an instance of the Bird object, get its current weight, then reset it, and finally get the current weight again:

 //create a new Bird with a weight of 40 var myBird:Bird = new Bird(40); //get the birds weight trace(myBird.weight); //now reset the weight myBird.weight = 25; //now get the weight again trace(myBird.weight); 

Again, we access the getter and setter methods to control the properties of the myBird instance, but they appear to be properties we are calling, not methods.

NOTE

With getter methods, there are never any parameters, just the result being returned. And with setter methods, there is one parameter, and nothing is being returned.


Now we have covered both properties and methods, and the final step is events.

Creating Events

Properties are pieces of information about an object. Methods are what objects do. Events are notifications about objects.

There are two ways to create events so that they can be used in Flash. You can create a callback event or a listener event. In this section, we will go over both.

Creating Callback Events

Callback events are blank methods that can be reassigned to individual instances of objects, but are called from within the object class.

Here is an example of creating a callback event:

 class Bird{     //create the callback event method     public var onLand:Function;     //create a method that will land the bird     public function landBird():Void{         //call the event         this.onLand();     } } 

As you can see, we create a blank function in the beginning of our class. We then create a method that will trigger the event automatically (normally, an event would be triggered within a condition, but in this example, we want it to be triggered no matter what).

Here is the code that will reside in the Flash file that is in the same directory as the preceding .as file:

 //create a new Bird var myBird:Bird = new Bird(); //set the callback event for this instance myBird.onLand=function(){     trace("the bird has landed"); } //call the method that will trigger the event automatically myBird.landBird(); 

In this example, we create an instance of the Bird object. We then set up the callback method for this particular instance for when the onLand event fires. Finally we call the method that will automatically trigger the event. If you test this movie, you will see that the message has been sent to the Output panel.

That was one way to create an event. The other way is a bit more complicated than callbacks, but is much more scalable and flexible to use when you get used to it.

Creating Listener Events

Listeners are another way your objects can have events captured. The difference between listeners and callbacks is that for callbacks, you are creating an event method on the instance of the object. For listeners, you create an object whose sole purpose is to listen to a certain event, and then you add that object to the instance as a listener.

It's a little complicated at first, but after we go through the example, it will be easier to understand.

To create listeners in external object classes, you need to import the Eventdispatcher class using the import keyword, like this:

 import mx.events.EventDispatcher; 

Importing classes is an important part of creating external AS files. It allows you to use methods from other classes within your own class without having to extend the class you import. You import classes directly from the Classes directory in the First Run directory of Flash 8. You separate subdirectories with dot syntax.

TIP

You can import all external AS class files of a directory by using a wildcard on that directory like this:

 import mx.controls.*; 

Now all class files in the directory mx/controls will be imported.


Now that you know how to import the class we need, let's see how to use it.

This is the code for creating an event that has listener support. We will use the dispatchEvent() method of the Eventdispatcher object after we initialize it in our constructor function.

 //import the object class we need import mx.events.EventDispatcher; class Bird {    //create two methods that will be used in Flash    public var addEventListener:Function;    public var removeEventListener:Function;    //declare the event we will use from the EventDispatcher object    private var dispatchEvent:Function;    //declare the constructor function    function Bird() {       //initialize the EventDispatcher to work with this object       EventDispatcher.initialize(this);    }    //create the method that will automatically trigger the event    function landBird():Void {       dispatchEvent({type:"onLand"});    } } 

The preceding code first imports the object class we need to have listeners. It then declares the object class as Bird. After that, it declares two methods that will be used in the Flash file. Then it declares another method from the Eventdispatcher object to be used in the Bird object later on. Then the constructor function is created, initializing the Eventdispatcher object to work with the Bird object. Finally, the method that will automatically trigger the event is created and it uses the dispatchEvent() method to send the event name to Flash.

That was the external AS file; here is the code for the Flash file:

 //create a new Bird var myBird:Bird = new Bird(); //create an object to listen for the onLand event var birdListen:Object = new Object(); //create the event for this object birdListen.onLand = function(){     trace("the bird has landed"); } //add the object to the instance of the bird as a listener myBird.addEventListener("onLand", birdListen); //now call the method to automically trigger the event myBird.landBird(); 

This code creates an instance of the Bird object. Then it creates a generic object that we will use as the listener. We then create the event with the generic object that will send a message to the Output panel when called. We then add the generic object to our instance of the Bird object class as an event listener. Finally we call the method that will automatically trigger the event.

Test the movie, and you will indeed see the message sent to the Output panel.

That ends the basic fundamentals of creating external AS files. Let's move on to an applied example.




Macromedia Flash Professional 8 Unleashed
Macromedia Flash Professional 8 Unleashed
ISBN: 0672327619
EAN: 2147483647
Year: 2005
Pages: 319

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net