Apr 10 2008

Write your first class ever in Flash AS3 with access to the stage and event dispatching

Published by admin at 1:05 pm under Basics, Flash AS3

The switch for many users from Actionscript 2 (AS2) to Actionscript 3 (AS3) can be a difficult one mainly because of AS3’s preference for an Object Oriented (OOP) style of programming. Once users realize this they are often thrown head first into the realm of class creation in flash with really no idea how to make this “class” interact with their timelines. The hope is that by the end of this article one will have a basic understanding of how to create, design, and implement a class.

Before we get started, here is the example code you can use to follow along.

Step number one consists in creating the actual “*.as” file and placing it in the correct place in relation to your “*.fla” file. (classpath) Generally speaking, people tend to place their class in subfolders that use the “*.fla” as its base folder. For instance, if you .fla is in “C:\wamp\MyProject” then that would be the base folder. The first subfolder tends to be called “com” and the ones after that either the person’s online alias or simply a descriptor name. For instance, using the same base class as above, I would put my classes into a folder with the path of “C:\wamp\MyProject\com\kylebrekke”. This keeps things very simple and clean, and its easy to post your classes online later. All people have to do is drop the “com” folder into their base folder and everything is ready to go. So, assuming you’ve setup your files in this way (and we will use my example for the rest of this article) lets dig a little deeper into the code.

Next you will need a basic frame of code for your class. Each class resides inside what Adobe calls a “package”. This really is just a set of related classes. Note, however, that only ONE class per package is allowed to be public, that is, only one class can talk to the rest of flash, the rest of the classes in the package can only talk to other classes inside the package. Here is the basic look of the starter package:

package com.kylebrekke {
}

Notice how after the keyword package you have a reference to the classpath using dot syntax. This is the same in windows language as “\com\kylebrekke” except we replace slashes with periods. After this we have to give the package a class to work with. We will call ours “testClass” to make it easy.

package com.kylebrekke {
public class testClass extends Sprite {
}
}

We make this class public, so its accessible to our timeline, we call it testClass, and it extends Sprite. Sprite is the preferred base class of Flash CS3 because it comes with everything you could need such as event listeneing and stage capability, but it is not bulky like some other extended classes. Unless you know for a fact you want to extend with something else, I recommend always using the Sprite class.

Next, we have to give our class a constructor function. This is the function that ALWAYS gets called first when someone instantiates your class. You are not required to put anything inside it, but it’s a great place to gather info that you know the class will need, or need set.

Now I haven’t previously mentioned what we will use this class for. I think it will be helpful for demonstration purposes if our class, once instantiated, takes a textfield already on the stage and checks its value, and if it’s a certain value then displays a new textfield. That being said, the constructor is a great place to take the reference to the already created textfield. I’m going to take a big leap in the code and place a bunch of things we need access to within the package.

public function testClass(alreadyOnStage:TextInput, s:Stage):void { // We are passing a reference of the Input Text into a class variable
// so that we can access it from anywhere inside our class
stageTextfield = alreadyOnStage;
stageTextfield.addEventListener(Event.CHANGE, checkText);

_stage = s;

// This custom text can be overriden by the getters/setters
customText.text = "Correct Text!";
customText.x = 250;
customText.y = 35;
}

Notice that the constructor has the same name as our class. Its also declared as public. These two things are vital and they will never change no matter the class. Next, notice the two parameters that are getting passed. One is a reference to the text field that we want to check, and the second is to the stage. This allows us to access things from the timeline that we normally wouldn’t.

Inside the constructor, we assign the parameters to their class variables so that we can access them throughout the class. This is a very typical method especially when you have a reference that you need access to outside the constructor function. In addition, we have added an event listener to the text input so that as a person types we are constantly verifying it against our predetermined text.

I almost forgot to mention how important it is to include to correct imports when working with a class like this. Without them the compiler will throw all types of errors at you that often come in the form of: 1046: Type was not found or was not a compile-time constant: Stage. If you get that error its because you forgot to import all of the necessary files for the compiler.

Here is the next piece of code:

private function checkText(evt:Event):void {
if (stageTextfield.text == "test text") {
_stage.addChild(customText);
dispatchEvent( new Event(correctText) );
}
}

The event listener calls a function that I named checkText. This takes the Event as a parameter, and this event is an object that has access to the target that called it. We could easily use that if we had more than one object calling this function, but since we don’t we will specifically check the text of the Input Text against our “test text” and if they are the same, we will add a new text field to the stage. Notice how I have referenced the addChild() of the stage and not of the class. If I were to forget the “stage” before addChild nothing would show up because the textfield would be added to the stage of our class, not the timeline. Thus, it is a very important piece of code.

The next piece is dispatching an event. You’ll notice that within the conditional statement of checkText, if we find a match then our class dispatches an event. This would be a great way to, for instance, make a “next” button appear on the stage from the timeline. I will show you that code a little further down the page. The important part of the dispatch function is that you should be dispatching an event. You have many possibilities including custom events, in this case we are just dispatching the even by name, but we could also pass on the Event.CHANGE event if we wanted the timeline to access to that as well.

Finally, I’d like to talk about the getters and setters. These are public functions that can make private variables accessible outside the class. The main reason you employ these as opposed to public variables is that you can control whether or not the variable has both capabilities, that is, to be read and written to. In addition, you can make alterations to the variable before passing it out of the class, which can be great leverage. Here is the code for the getter and setter of the customText variable:

public function get customizedText():String {
return customText.text;
}
public function set customizedText(s:String):void {
customText.text = s;
}

In this case, I have not opened up the entire textfield to editing from the user, only the text portion of it. This can protect your code from getting sloppy and unmanageable in the future and it is an important piece of structure to build into all of your classes. Now, my class has a property that can be set very easily simply by doing code that looks like “instance.customText = “new text”;” and instead of “Correct Text” our textfield will show something different.

Ok, finally we can move on to our instantiation code that will be inside of our “*.fla” file. I’ll post all the code since it is not very much and discuss it point by point.

// Import the proper files for the compile
import com.kylebrekke.testClass;// Instantiate the new clas
var test:testClass = new testClass(myInput, stage);

// Add the event listene
test.addEventListener(testClass.correctText, nextQuestion);

// Use a setter to set custom tex
test.customizedText = "Bravo, correct answer!";

// This function is called by the event listener when the
// text is correct
function nextQuestion(evt:Event):void {
// You could place code to move to a next question here
}

stop();

First, we have again imported our code using the correct dot syntax. Right after that we provide the instantiation code. This code takes two parameters, the input text and the stage. The input text MUST be already dragged onto the stage and been given an instance name, in this case I called it “myInput”. The stage variable “stage” will always be the same if you are passing from the timeline to the class.

After that I added an event listener that listens for the custom event of correct text. Notice that the event listener is placed onto “test” which is an instance, but that in order to access the constant’s name that we are dispatching I use the class. This is because the constant that I defined in the class is “static” and does not need to be instantiated. You must make sure that if you follow the same sort of coding that I am practicing here, must use the instance name and the class name in the proper places or the compiler will throw an error. This can be confusing at first, but you’ll get the hang of it in no time.

Just below that I am using a setter to reset the text that will display when user types in the correct text into the Text Input. You’ll see once you execute the code, it should be self-explanatory.

Finally we have the function called by the text. Now I didn’t actually write and code for the next question, but I did let you know that this function would be where you could execute the code for displaying a button for instance that you only want to display once the person has typed in the proper input.

Anyway, that is an explanation of the code piece by piece. I hope you found this useful. Please post any question or comments you may have.

Another great tutorial if you need some help is Senocular’s Beginners Guide.

Here is the example file for download so you can follow step by step and compile it yourself to see how it work. Enjoy!

(Quick update on using root vs. stage)

Popularity: 45% [?]

10 responses so far

10 Responses to “Write your first class ever in Flash AS3 with access to the stage and event dispatching”

  1. [...] you’d like to see an example of these event listeners in action you can read the article Write your first class ever… with event dispatching. Please do not hesitate to leave any comments or questions you might have on the feedback [...]

  2. Masuelocaon 12 May 2008 at 2:18 am

    Please I’m much delighted with the article and would try to view more next time. How would you then help someone design a preloader for a web page? As in having ACS3 and would like to design a flash preloader. Where do I begin my work? I don’t even see any icon on downloading that relates to open a new project or file so that I can try to implement your tricks.
    Masueloca
    Uganda.

  3. adminon 12 May 2008 at 10:20 am

    Hi Masueloca,
    I’m happy you enjoyed the article! Unfortunately, I haven’t quite gotten around to making a universal preloader class or writing a tutorial on it personally, I have however, put a link up that has some video tutorials which should get you started in the right direction:

    http://www.kylebrekke.com/wordpress/2008/preloader-class-video-tutorial-for-as3/

    Let me know if you have any specific difficulties with the preloader and I’ll do my best to help you out.

    Thanks,
    Kyle Brekke

  4. mattdon 17 May 2008 at 3:04 am

    Thanks Kyle

    It’s taken me quite a while to shift from AS2 to AS3. This post, and your others, have really helped me understand the structure of AS3; objects, methods and events.

    Great stuff. Many thanks.

    Matt

  5. adminon 17 May 2008 at 7:57 am

    Its my pleasure Matt. Keep checking back every so often as I try to post something new about once a week (maybe even more often since summer is starting). Shoot me an email if you ever need help figuring something out in AS3.
    All the Best.
    Kyle

  6. Jake Rutteron 03 Jun 2008 at 12:24 pm

    Great Tutorial, this is very helpful. I have been working in AS3 for the past 6 months, but only recently taking the jump over to OOP. You can still do procedural programming in AS3, although its probably not the best bet. I took my first stab at creating a custom class that adds an image to the stage by way of a preloader, it uses events to track the progress. Its pretty sweet, you can check it out here:

    http://onerutter.com/flash/part-2-using-loaderinfo-events-to-create-reusable-imageloader-class.html

  7. adminon 03 Jun 2008 at 2:49 pm

    Thanks Jake, I’m glad it helped! I think you’ll find the jump to OOP to be extremely helpful in the long run. Any large project will otherwise quickly become unmanageable without it. Feel free to post any questions or suggestions you have for me on the site, I’ll keep trying to post new tutorials and projects when I get more time.

    Best Regards,
    Kyle

  8. Taraon 01 Jul 2008 at 1:19 pm

    Hi and Thanks for this great tutorial.
    I was wondering if you could make one that is a basic to understanding how classes communicate to each other.
    Thanks

  9. adminon 11 Jul 2008 at 9:39 am

    I’m glad you liked it. I most certainly can write a tutorial like that. Its now on my list of things to do.
    -Kyle

  10. [...] etc) but also the DisplayObjects that reside there. If you played around with the files provided in the original post and tried to do something like: [Copy to clipboard][-]View CodeACTIONSCRIPTprivate function [...]

Trackback URI |