събота, 8 октомври 2011 г.

ACTIONSCRIPT 3.0 BASICS

Classes and OOP


I’m going to try to cover all the basics in AS3 in this blog.

If you think you do not have any familiarity with classes, you may be wrong. If you’ve written any code
in Flash, chances are you used several classes. A class simply refers to a type of object. MovieClip is a
class referring to—you guessed it—movie clips. Text fields, movie clips, buttons, strings, and numbers
all have classes.
A class basically has two things associated with it: properties (data or information) and behaviors
(actions, or things it can do). Properties are essentially variables that hold information relating to the
class, and behaviors are just functions, though when a function is part of a class, we usually refer to it
as a method.

If you have used Flash for a while, you know that you can create a symbol in the library, and then
create several instances of that symbol on the stage. Similar to the relationship between symbols and
instances, classes are templates, and objects (also known as instances) are individual manifestations of
a particular class. You can make a simple class like this:

package {
public class MyClass 
{
public var myProperty:Number = 100;
public function myMethod() 
    {
       trace("I am here");
    }
}
             }


Let’s run through the code. First we have something that is new even to AS 2 class veterans: the package
statement. Packages, simply put, are a way to group related classes together.Still, though, you’ll
need to include the package keyword and brackets as shown in this example. This is also known as the
default package.
Next comes the class definition itself. Another change here for you old timers: Classes can now have
access modifiers. An access modifier is a word that specifies what other code can access the code in
question. The word public here means that this class is accessible by any code outside of the class.The classes will be public. If you decide to study more about AS 3,
you’ll find out about nonpublic classes and even multiple classes within a single class file.
You can see the class has a name, MyClass, followed by another pair of opening and closing brackets
that enclose the class.
Within the class are only two things: a variable named myProperty and a function named myMethod.
These will become properties and methods of any instance of this class you create. Again, for
properties and methods, the word public means that any code outside the object will be able to
access that property or call that method. If you create properties or methods that are meant only for
use within the class itself, you can label them private, which prevents them from being messed with
by any code outside the class. AS 3 also adds the modifiers internal and protected. An internal
property of a class can only be accessed by other classes in the same package, and protected means
that a property can only be seen by classes that extend this particular class (which is pretty much what
private was in AS 2).
I’m filtering out a large portion of the more complicated stuff, and a lot of the
stuff I am describing here won’t be used all that much in the book.
A class is written and saved in an external text file named the same as the class, with the suffix .as, as
in MyClass.as. You can create the file by using the ActionScript editor in the Flash CS3 IDE, Flex Builder
2, your favorite code editor, or any other text-editing program.
If you are using the Flash CS3 IDE, you’ll also be creating an FLA. The class files you create must be in
the same directory as your FLA file if you’re using the default package. If you’re using a package structure,
the root directory of that structure should be in the same directory as your FLA. Alternatively,
you can store these classes somewhere else, and add that directory to your class path. The class path
is simply a list of directories. When you specify a class name in your code, Flash will search those directories
for a class with that name. You’ll stick to the default package,
and you can keep the classes alongside the FLAs.

Packages


Again, packages are mainly there to organize classes. Packages are structured according to the directories
in which they are located, and they can be nested several layers deep. Each name in the package
refers to an actual folder, with the names separated by dots.(It is a common convention to
use domain names as packages. This ensures the package will be unique.)


In AS 2, you would declare the class with its full package name, like so:
class com.AS2.makingthingsmove.Utils {
}

In AS 3, the package part goes with the package declaration, and the class part goes with the class declaration,
like this:

package com.AS3.makingthingsmove {
public class Utils {
}
}


Imports


You just have to write it the one time. From there on out, in that file, you can now just write Utils to
refer to that class. Now, in AS 2 imports were a great convenience, but in AS 3 they have become
necessities. The fact is that in AS 3, you must import any class you use from a different package, even
if you do write out the full name each time, or your code will not compile. Flex Builder 2 actually has
a neat feature that will automatically add the import statement whenever you type out the full package
of a class. In any case, it is up to you to make sure that the import is there. This makes that class
available to the compiler to use when creating your movie.









Constructors


You can set a constructor for the class, which is a method that has the same name as the class and is
automatically called when a new instance is created. You can pass arguments to the constructor as
follows.
First, create the class:


package {
public class MyClass {
public function MyClass(arg:String) {
trace("constructed");
trace("you passed " + arg);
}
}
}


Then, assuming you are working in the Flash CS3 IDE, create the instance right on the timeline:
var myInstance:MyClass = new MyClass("hello");

This should trace "constructed" and then "you passed hello". If you are working in Flex Builder 2
or the free SDK, you’ll have to just take my word for it that this works for now. You’ll get plenty of
hands-on practice later.

Inheritance


A class can inherit from, or extend, another class. This means that it gets all the properties and methods
that the other class has (unless the properties or methods are marked as private). The subclass
(the one that is inheriting) can then add additional properties and methods, or change some of the
ones from the superclass (the one that is being extended). This is done by creating two separate
classes (in two separate .as files) like so:

package {
public class MyBaseClass {
public function sayHello():void
{
trace("Hello from MyBaseClass");
}
}
}

package {
public class MySubClass extends MyBaseClass {
public function sayGoodbye():void {
trace("Goodbye from MySubClass");
}
}
}

Remember that each class must be in its own file named after the class name, with the .as extension,
so you will have a MyBaseClass.as file and a MySubClass.as file. Again, using the Flash CS3 IDE, make
a new FLA file and save it in the same directory as the two classes. Now, on the timeline you can make
a couple of instances and see what happens:

var base:MyBaseClass = new MyBaseClass();
base.sayHello();
var sub:MySubClass = new MySubClass();
sub.sayHello();
sub.sayGoodbye();

The first instance has no surprises. But notice that the second one has a working sayHello method,
even though MySubClass does not define sayHello. The class inherited it from MyBaseClass. Also
notice that it added a new, additional method, sayGoodbye, that the base class does not have.
Next, say you want to change an existing method from the base class in the subclass. In AS 2, you
could simply redefine it. In AS 3, you must explicitly override it by using the word override in the new
definition:

package {
public class MySubClass extends MyBaseClass {
override public function sayHello():void {
trace("MySubClass");
}
public function sayGoodbye():void {
trace("Goodbye from MySubClass");
}
}
}

Notice that sayHello, when called from MySubClass, now has a totally new message, as the original
method has been overridden. Realize, of course, that a private method could not be overridden, as it
is only accessible from within its own class.

Creating your document class

You now have enough information about classes to start writing one for actual use. A few times I’ve
mentioned how important classes are in creating an AS 3–based SWF. This is because of a new concept
introduced in AS 3, the document class. Basically, a document class is a class that extends Sprite or
MovieClip, and is used as the main class for your SWF. When the SWF is loaded, the constructor of
that class will be called. That will be your entry point for anything that you want to have happen in the
movie, such as creating additional movie clips, drawing graphics, loading assets, and so forth.
If you are coding in the Flash CS3 IDE, using a document class is optional. You can always just go on
writing code on the timeline. But if you are using Flex Builder 2, or the free Flex SDK, there is no timeline
for you to write code on. The only way to get code into the SWF is to put it in classes. In those
tools, everything revolves around that one mighty document class. Without it, there would be no SWF.
Here is the skeleton document class I promised you earlier:

package {
import flash.display.Sprite;
public class Example extends Sprite {
public function Example() {
init();
}
private function init():void {
// sample code goes here
}
}
}

None of this should be new to you if you’ve followed along with the preceding sections, but here you
have it all together in one place. I’m using the default package, and importing and extending the
Sprite class. The constructor has one line that calls the init method. It would certainly be fine to put
all of your code into the constructor, but it is usually considered a best practice to limit the amount of
code in a constructor, so I shuffle it off to another method. When the movie is compiled and run, the constructor will call init, which will run your code.


The display list

Prior to AS 3, you could create a number of different types of visual objects in a Flash movie, including
movie clips, graphics, buttons, text fields, bitmaps, components, and basic shapes. These objects
weren’t really organized in a hierarchical structure, and they all had very different ways of being
created, destroyed, and manipulated. For instance, movie clips could be attached, duplicated, put on
stage in the IDE, or created from scratch. Text fields could be created from scratch or created in the
IDE. When you get into bitmaps, videos, components, and the rest, it seems like each type was created
on a different planet and was shoved in to Flash and forced to work with the others.
The differences among these objects has been totally addressed in AS 3. Just about any type of object
that you can see on stage is created from a class that extends the DisplayObject class. In other words,
all of these objects are part of the same big family now, and they all behave the same basic way, in
terms of how you create them, put them on stage, destroy them, and manipulate them on stage.
The code for creating a sprite, a movie clip, or a text field is now very similar. In fact, all display objects
are now created the same way you would create any other type of object, with the new operator. To
prove the point, here is how you create these three items:
var myTextfield:TextField = new TextField();
var myMovieClip:MovieClip = new MovieClip();
var mySprite:Sprite = new Sprite();
It doesn’t get much simpler than that, does it?
As you saw in previous examples, if you’ve created a movie clip or sprite, you can now draw some content
into that object, like so:
mySprite.graphics.beginFill(0xff0000);
mySprite.graphics.drawCircle(0, 0, 40);
mySprite.graphics.endFill();
But if you try it just like that, you won’t see much. This is where our discussion of the display list comes in.
The term “display list” is new, but if you’ve worked with Flash for a while, it shouldn’t be a foreign concept.
Think of it as a tree of all the visual objects in your movie. At the base of the tree is the stage,
which is visible by default. On the stage, you might have several movie clips or other types of visual
objects (text fields, shapes, etc.). When you add them to the stage, they become visible too. Within
those movie clips might be other movie clips or other visual objects, and within those, others. That is
basically your display list.

The biggest difference between how the display list works in AS 2 and AS 3 is that in AS 2, when you
created a movie clip by attaching it or using createEmptyMovieClip, you had to specify where it
would go on the tree at the time of creation. At that point, the movie clip would be created and put
on the list at the specified location, and that’s where it would stay. Short of removing the clip, there
was no way to change its location on the list or take it off the list without destroying it completely.
In AS 3, when you create a new movie clip, sprite, or any other display object, it is not automatically
added to the display list. Note that in the sprite example just given, there is no parent or depth mentioned
when the sprite is created. It is able to exist and be manipulated without being on the display
list.

If you take the term “stage” literally, you can imagine these objects as actors behind the curtains, off
in the wings, suspended above the stage, or even crawling around underneath it. You can’t see them,
but they are all there, busy getting ready for their big entrance, when they will jump on stage and steal
the show.

So far, we have a tree metaphor and a theater metaphor—how about one more? We can also think of
the display list in terms of a family, as a series of parent/child/sibling relationships. When you add
something to the display list, the object you add it to is the parent, and that new object is the parent’s
child. Thus, it makes sense that when you add an object to the list, you do so with the addChild
method.
Your document class represents the base of the tree (or the great-granddaddy of all other display
objects, if you wish). It is automatically visible, and you start off by adding children to it. So, as you saw
in earlier examples, to make a sprite or any other display object visible, you call the addChild method,
passing it the newly created sprite:
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0xff0000);
mySprite.graphics.drawCircle(0, 0, 40);
mySprite.graphics.endFill();
addChild(mySprite);
If you want to try this, put the code in the init function of the skeleton class presented earlier. Note
that it will be placed at point 0, 0 initially; you can change it by adjusting its x and y properties.
Also note that there is no mention of depth here, as there was when creating new movie clips or
attaching them in AS 2. Depth management is largely automatic, although there are methods to add a
child at a particular depth or change its depth, which we will get into as they become necessary.
To remove an object from the display list, call removeChild, passing in a reference to the actual child
object. The first key thing to realize is that removing a child does not destroy it! It continues to exist
in the exact same state it was in prior to being removed, and it will be in that same state when you add
it back on the display list. In other words, if you have drawn some shapes into the child, or loaded
some external content into it, you won’t have to redraw or reload that stuff when you put it back on
the list, as you had to in AS 2.
The second key thing to realize is that when you put the child back on the list, you have the freedom
to put it back on the list wherever you want. This is known as reparenting and is very exciting (at least
to me). You can now remove an object from one movie clip and attach it to another one, in the exact
same state it was in when you removed it, which was not possible before. In fact, you don’t even need
to remove it. Because a child can have only one parent, adding it to another parent automatically
removes it from the first.

The following class demonstrates reparenting:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
public class Reparenting extends Sprite {
private var parent1:Sprite;
private var parent2:Sprite;
private var ball:Sprite;

public function Reparenting() {
init();
}
private function init():void {
parent1 = new Sprite();
addChild(parent1);
parent1.graphics.lineStyle(1, 0);
parent1.graphics.drawRect(-50, -50, 100, 100);
parent1.x = 60;
parent1.y = 60;
parent2 = new Sprite();
addChild(parent2);
parent2.graphics.lineStyle(1, 0);
parent2.graphics.drawRect(-50, -50, 100, 100);
parent2.x = 170;
parent2.y = 60;
ball = new Sprite();
parent1.addChild(ball);
ball.graphics.beginFill(0xff0000);
ball.graphics.drawCircle(0, 0, 40);
ball.graphics.endFill();
ball.addEventListener(MouseEvent.CLICK, onBallClick);
}
public function onBallClick(event:MouseEvent):void
{
parent2.addChild(ball);
}
}
}

The class creates three sprites: parent1, parent2, and ball. The parent sprites are added to the display
list directly, and squares are drawn in them. The ball sprite is added to parent1, so it is now on
the display list and visible.
When the ball is clicked, it is added to parent2. Note that there is no code to change its x, y position.
It moves because now it is within a different sprite, which is at a different position. Also note that the
dynamically drawn circle remains, even though the sprite was removed and added back.

I hope this is enough for starting developer.