Video Tutorial - Organizing your class files with namespaces

February 13th, 2008 . by polyGeek

This video tutorial begins where the first one left off. Here you’ll learn to place your class files inside a unique name space within your global class path.

If you’ve ever downloaded someone else’s class files and couldn’t get them to work this might help.

[ download FLV ]



Adobe affiliate links help support video tutorials here at polyGeek.com

Start building web applications with Adobe Flex Builder 2

Notes:

  • An import statement adds that class to your SWF when it’s compiled and adds on to the file size of your SWF. If you’re importing a class but not using it then you’ll bloat your SWF filesize unnecessarily. This happens from time to time when you edit your code and remove a call to a class and forget to remove the import statement.

Lee Brimelow at gotoAndLearn.com did a video tutorial covering the use of custom classes. I’d suggest watching that if you still have any questions.


Video Tutorial - Introduction to using class files

February 13th, 2008 . by polyGeek

If you’re using class files ( .as ) you need to know where to put them. It can be a little confusing because they can go in more than one place. In the video below I’ll cover the basics of where you can put these files and make them work.

[ download FLV ]

Related videos: Class files with name spaces and the import statement



Adobe affiliate links help support video tutorials here at polyGeek.com

Start building web applications with Adobe Flex Builder 2

Lee Brimelow at gotoAndLearn.com did a video tutorial covering the use of custom classes. I’d suggest watching that if you still have any questions.


Using the Delegate class to manage scope

October 25th, 2007 . by polyGeek
Download code samples

The Delegate class is used to specify the scope that a method/function operates in. It’s primary use is for Flash components and managing the events they dispatch. I personally don’t use the Flash components so I never came across it. If you’ve never heard of it either then get ready for a really cool addition to your coding toolbox.

Suppose you are creating a setInterval. You would do something like this:

That’s pretty much the way I always create intervals. When you run it you’ll get undefined for this.

The other way to create an interval is like this:

That solves the problem of scope in the function call. But there’s yet another way:

The Delegate class is like a Jedi mind trick for methods/functions. It says, “this is not the scope you are running in. Use this one instead.”

The only downside I can find with using Delegate is that you can’t pass arguments to the method/function that you call. At least I can’t find any documentation on that.

Note: a reader commented below that there is a way of using the Delegate class, or something like it, that does allow for passing parameters. Here is the link: person13.com/articles/proxy/Proxy.htm

Using the Delegate in this example is a little more code to write for the same result as the second approach but this isn’t really what Delegate was meant for.

setIntervals could get a little messy when you’re using them inside classes. You pretty much had to create nested functions so that you would be able to clear the interval later. Or the setInterval number could be a property of the class but that comes with it’s own baggage.

In my book this is where Delegate really shines.

That is a nice clean way to create methods that can be run on an interval and cleared when wanted.

Making Mouse listeners

When you create a Mouse Listener the scope of the function callback is the object that is listening to the Mouse events. And that’s usually not the scope you want to run in because it’s sort of like an island in the middle of a huge ocean.

The standard Mouse listener looks like this:

You’re sort of left hanging on the scope of the MouseListener1 object there. Not a whole lot of good. Using Delegate we can make that function run in any scope we want to. For this simple example it will run in the scope of the _root.

Another solution is to attach the scope that you want to the listener object like this:

That’s pretty much the way I did things before learning about Delegate. This approach works fine for most occasions. In my estimation the best reason for using Delegate is that it’s just more elegant. Using this.thisRef seems like a bit of a hack to me. Although I’ve used it countless times.

Creating Interface elements

Here’s an example of how you might use Delegate in a class where you are creating user interface elements, otherwise known as buttons. :-)

In this class I create a simple button. I pass along a MovieClip to create the visual elements inside of, the button label, the width and height of the button, and weather to use Delegate to manage the onRelease event or attach a reference to the button instance via thisRef.

The basic problem when creating interactive elements in a class is that when the user clicks on one of them the scope is automatically the MovieClip they just clicked on. Not the class that created the button in the first place. That’s where the data, or access to the data, would be handled.

There are numerous ways to handle this problem. You could create static methods in a class and pass along information. And you can dynamically attach properties to the MovieClip when it’s created. In that way it can identify itself. But it can’t get access to the instance of the class that created it without attaching this inside the class, as I did with the Mouse listener above.

By using Delegate you can make the button operate in the scope of the the class instance which created it. That can be very handy. The downside is that now you’ve lost reference to the actual MovieClip that was clicked on. That can be solved very simply by keeping a reference to the MovieClip as a class property.

Here is an example:

You can see that with this class you can either use Delegate or attach this to the Button instance. Here’s an example of two instantiations that use the two approaches.

No need for Delegate in Actionscript 3

The good news is that in Actionscript 3 events are handled completely differently, or should I say correctly. In Actionscript 1/2 events were sort of added willy-nilly to the language/player over time. With Actionscript 3 we can create classes and get event objects sent to the callback. Essentially scope is much easier to handle. But that’s another story.

You can read more about the Delegate class and components at Actionscript.org.


Pre-Object Oriented Programming (OOP) for Actionscript, part 5

July 22nd, 2007 . by polyGeek

Errors, Errors, everywhere but nary an idea what’s wrong

That’s the feeling we all get when we’re trying new things in Actionscript. Our FLA won’t publish because there’s some error and you’re thinking, “What the Frak does that mean?”

So here are a handful of common error messages that you get when using classes and what they mean.

The class or interface ‘<SomeClassName>’ could not be loaded.

You either have the path/namespace or the class name wrong. It’s probably a typo somewhere. As an example, if you are using the Holtzman class and you wrote this code:

var h:Holtzman = new Holtzman(....

You would get the above error because you either forgot to use the full namespace or to import the class. You could fix that by either doing this:

var h:com.polygeek.utils.Holtzman = new com.polygeek.utils.Holtzman(....

or this

import com.polygeek.utils.Holtzman;
var h:Holtzman = new Holtzman(....

The class being compiled, ‘<SomeClassName>’, does not match the class that was imported, ‘com.polygeek.utils.SomeClassName’.

This is easy. You have a class that you created in a specific namespace but you forgot to tell the class what namespace it’s in. Here’s an example: you have a class <SomeClass> in the com.polygeek.utils folder and the class declaration looks like this:

class SomeClass {

It should b:

class com.polygeek.utils.SomeClass {

The property being referenced does not have the static attribute.

This one is a tough one to describe unless you understand OOP in the first place. By example suppose you wrote the following code:

MovieClip._alpha = 50;

You know that doesn’t make any since because _alpha is a property of an individual MovieClip. You can’t set the _alpha of all MovieClips with code like that above. You would have to go to each instance of all MovieClips and change their _alpha individually.

A constructor may not specify a return type.

The constructor cannot have a return type, not even :Void. So your constructor looks like this:

public function SomeClassName() {...

Not like this:

public function SomeClassName():Void {...

As I think of more common errors I’ll add them to this page. Feel free to suggest your own in the comments and I’ll add them here.

Happy debugging.


Pre-Object Oriented Programming (OOP) for Actionscript, part 4

July 22nd, 2007 . by polyGeek

A common discussion I’ve had with other developers about learning Object Oriented Programming in Actionscript is: for people new to OOP which is better to learn: Actionscript 2.0 or Actionscript 3.0.

Here are my thoughts on the subject:

If you already know a little bit of Actionscript 2.0 and you want to expand your skill set then go ahead and learn OOP for AS2. You can then pick up AS3 when the need arises. I believe that there will be designers and developers delivering Flash projects using AS2 for years to come.

If you are a designer/developer working on small projects like creating video interfaces, or brochure type sites that are animation intensive then I suggest learning AS2.

On the other hand if you plan to work on projects like building Rich Internet Applications that can scale to include all sorts of components and using dynamic data from web services or Flash Remoting, etc. then you should think about jumping straight into AS3.

The gray area comes if you expect to be building widget type Flash projects. In that case you could go either way. You might be more productive right off the bat with AS2 and OOP but down the road you will probably want to start picking up AS3 and OOP.

The advantage to OOP in AS3 is that it is much more rigorous in how it treats code. Things that you can get away with in A2 will cause errors in AS3. And that’s a good thing because it helps you debug your code faster. The downside is that some things that are very simple to do in AS2 become a bit more involved in AS3. But things that are very code intensive in AS2 become trivial in AS3.

I hope I have helped to confuse you beyond repair. Now get to work. :-)

In part 5 of this series I’ll cover a few of the common error messages you’ll get while using classes and what they mean.


Pre-Object Oriented Programming (OOP) for Actionscript, part 3

July 22nd, 2007 . by polyGeek

Have you ever been working on a project where you’re writing some Actionscript and you think to yourself, “I know I’ve done this before. Where is that code. It’s in an FLA around here somewhere . . . ”

That problem is one of the things that object oriented programming is good at solving. It helps you externalize your code and organize it so that you can reuse those common bits over and over.

Thus far the classes that we have created in parts 1 and 2 have been written in .as files sitting in the same folder as your FLA. Sometimes that’s okay because those classes might be pretty specific for the project you are working on. But what if you have written some methods that could be really useful for other projects. You don’t want to have to copy that .as file to other folders just to use it.

The Flash authoring tool gives you a way of putting your commonly used class files in one location that can be accessible to all of your FLAs. No matter where they are on your computer.

Here’s what you need to do:

  1. Open the Flash authoring tool
  2. From the menu bar select Edit -> Preferences
  3. Select Actionscript from the Category nav on the left
  4. Click on the Actionscript 2.0 Settings button
  5. Click the “+” button to add another Classpath [see image below]
  6. Now click the target button - it’s the one in the center. This will allow you to browse to the folder where you’re going to put your classes.
    • Note: this is a very important folder. You don’t want to put it somewhere where it could accidentally be moved or deleted.
    • However, you want to be able to get to it easily. Plus, you might need to zip the files up in this folder to send to other people.
    • Remember, you cannot publish your FLA if you don’t have your class files. So if you’re working on a project with someone else you will need to share the files in this folder with them.
  7. All done? Click Ok

You can see that my Classpath is : C:\Documents and settings\polyGeek\Desktop\FlashSpace\GlobalClasses

Actionscript Settings Global paths

Now that we can write reusable code what should we do first? One of the things that I have to do in just about every project is load external images and SWFs. If you’ve done this yourself you realize it’s a bit of a pain. You have to create listeners, and functions, and all sorts of things. I think it would be great if we had a utility that could handle all this for us.

Here’s the code below for a utility that I have written to make it easy to load external assets into your SWF. A detailed explanation of how to use it follows.

First off take a look at line 14.

class com.polygeek.utils.Holtzman {

That’s a bit different from what you’re used to in creating classes thus far. What’s up with that?

Suppose you wrote a class, we’ll call it, FlashUtils. You put it in your global classpath and use it on a number of your projects. Everything works just fine until you download someone’s class that does some really cool stuff but its name is also FlashUtils. Now what?

Now you know that you can’t change the name of your class because then you would have to go back to every project that uses it and change the name there as well. And you don’t want to mess with someone else’s code.

The solution is that everyone puts there classes in a unique namespace. One thing you can be sure of that is unique is an internet domain name. So my global classes are in com.polygeek. Everything that comes after that are for my own organizational purposes. The Holtzman class is on the folder utils because it’s a utility.

Another thing to note is that classes are given names that reflect their purpose. You might be wondering what Holtzman is. If you hadn’t guessed by now I’m a geek and being a geek I like to chose geeky names for things. Is it consistent with best practices? Maybe not but that’s what you get for learning object oriented programming from a philosophy major. :-)

Back to using this Holtzman class. Go to your global class path that you set up from above and create a sub folder named com. And inside of that create a folder named polygeek. And once more for the utils. Notice that all the folder names are lower case which is consistent with best practices - sometimes I do things right.

Now create an .as file named Holtzman and paste the code from above into it.

Here’s how you use the class.

Create an FLA and paste the code below into it.

Publish and you should see two images - the polyGeek logo - one rotated +15 degrees and the other -15 degrees. And one of them has smoothing turned on. You can see that if you resize or rotate an image you probably want to use smoothing.

Here’s a quick synopsis of what’s happening:

  1. When you instantiate the Holtzman class you pass, at a minimum, the MovieClip to load the image into and the path to the image/swf.
  2. If you would like to do something like resize the image you have to wait until it has completed loading. That’s what the onImageLoaded function is for. You can name that function anything you like.
  3. Any parameters passed to the Holtzman class, after the smoothing: true/false, will be attached to the external asset you loaded so that you can access them in your callback function. That’s useful if, for instance, you are loading a series of images and you want to rotate each one a different amount. You can make up a variable name, like rotateThisMuch, and then the value you want to rotate to.
  4. The callback function you specify receives on Object of type MovieClip. That MovieClip will have a property of rotateThisMuch with the value you specified in the next parameter. This is an added feature that you probably won’t need very often but when you do it comes in very handy.

The great thing about all this is that you don’t have to understand any of the code inside the Holtzman class to use it. All you need to know is how to instantiate it - lines 16-20 and 22-26 - and what parameters to pass to it.

Word of warning: when you create a class that gets used across projects you have to resist the urge to modify it. For example, if you changed the order in which the class accepts parameters then all the places where you used it before would be broken.

Also notice that when you accessed the Holtzman class you did so through the constructor. Meaning your instantiated the class to create a new object. In this case it’s rather trivial but that is a new object and so you’ve now done object oriented programming.

Congratulations.

I would now suggest that when you feel comfortable with what you’ve learned to this point that you read Colin Moock’s book: Essential Actionscript 2.0. It’s pretty much the definitive source of learning OOP in Actionscript.

In part 4 I’ll give you my two-cents on weather or not to start learning Actionscript 2.0 or Actionscript 3.0 first.


Pre-Object Oriented Programming (OOP) for Actionscript, part 2

July 21st, 2007 . by polyGeek

In the first part of my Pre-OOP lessons you learned how to use classes as a substitute for _root or Global variables. It is an approach that is far from best practices but it does get you initiated to the syntax of classes and Actionscript.

In part 2 we’ll build on the basics that you learned and start applying some of those best practices.

Now you know how to create a class and add some public static properties and methods to it. You might be wondering what’s up with the public part. It’s really pretty simple. Anything that is public can be seen from outside of the class, like from your published SWF. But if you changed those publics to privates you wouldn’t be able to access those properties from any code unless it is inside the class.The next step in learning object oriented syntax is to make all of your properties (variables) private.

You might be thinking, “Doesn’t that defeat the purpose of what I learned in part 1? Not at all, you’ll still be able to access your properties (variables). You’ll just do it in a different way.

This is what you did before:

This is what you’ll do now:

The only difference is that all of the properties are now private and there are 4 new methods - 2 for each property - that we use to interact with those properties. Those are the getters and setters.

If you look at this code it really looks like a lot of extra work just to get the same thing done. But there is a method to this madness.

Here’s the reason for that. Suppose you have a property, well call it hourOfDay, which is a number that represents the hour of the day. You know that it’s a number between 0-23 in all cases. The old approach to programming is to simply update the value hourOfDay directly. The problem with that is that if you make an error you might assign a number that is greater than 23. Or it could be a decimal value when you always intend for it to be an integer.

There are any number of mistakes that could happen in your code that would allow you to assign a value that is out of range.

To fix that you make hourOfDay private so that you cannot access it directly. Then you create a method (function) to update the variable - set - and another one that retrieves the value - get. I’m going to make a new class for this and call it TimeTracker. (This is a file named TimeTracker.as that sits right next to my FLA file.

It’s just a convention to make the method names start with get and set. I could have named those methods anything I wished but it makes it more readable to prepend get/set.

Note: there is another syntax that is commonly used for getters and setters that would look like this:

public static function get hourOfDay():Number { ...

I prefer to use the former but they both do the same thing.

Now back in my FLA I’ll write this code:

What’s great about this approach is that you will get a message in your Output window any time you make an error trying to update hourOfDay incorrectly. Which makes it much easier to fix your code when things go wrong.

If you step back and think about it here’s what you’ve learned thus far:

  1. You can create a class where you can store variables that you want to be able to easily access from any line of code in your FLA.
  2. You have created properties that cannot be directly accessed.
  3. You have created methods through which your can get and set the value of your properties.

Just that little bit right there is a huge step in writing code that is easier to debug and maintain. Trust me: it will pay huge dividends. While it may be a pain to write all those getters and setters they do go pretty quick. Once you get used to it you’ll just fly through creating them.

One added bonus is that all those getters and setters look like you have written a lot of code. So when you’re showing your manager something in your code they’ll see long scrolling lines of code and think you’ve put in a lot more than you actually have. Which is also another argument for commenting your code but that’s another story. :-)

In part 3 I’ll show you how to use what you’ve learned so far to make your code more reusable.


Pre-Object Oriented Programming in Actionscript, part 1

July 5th, 2007 . by polyGeek

Introduction

This series of articles are not intended to teach you object oriented programming. They are intended to teach you the framework and syntax around OOP. This is like the Pre-Calculus class you took before taking Calculus. It makes things a lot easier down the road. At least that’s my hope.

Pre-Object Oriented Programming

The problem with learning to apply OOP practices in your Actionscript is that it’s a radical departure from your existing workflow. Unless you have time to sit down and peruse Colin Moock’s Essential Actionscript book, a few times, then it’s just a frakking pain to try to switch over all at once when you know full well you could go about doing things as you always have and get the job done.

Besides, who cares if you use OOP practices? It’s likely that no one but yourself will ever see your code. And if the end result is the same then why bother. Right?

Wrong. Adopting OOP coding into your projects will make them much easier to write in the first place, and they’ll be easier to update later.

Plus, you can put it on your resume and make more money. :-)

Note: I’m assuming here that you are comfortable with at least creating variables and the occasional function. If you know how to pass parameters to a function then you’re in good shape and if you know how to return a value from a function then everything’s shinny.

The best way to learn OOP in Flash Actionscript is to start with the syntax. Here is a list of some of the things you don’t need to know in order to get started.

  • instantiate,
  • public vs private,
  • instances,
  • objects,
  • constructors,
  • methods and properties,
  • design patterns

Yep, you heard me. Skip all that crap. You can pick that stuff up later.

No more _root

When you write code do you create variables on the _root, like say myVariable, and then refer to them from code inside MovieClips all located all over your FLA with: _root.myVariable? Well, no more.

Here’s what you do:

  1. Create an FLA and save it with any fileName you want.
  2. In the same folder as the FLA create a new .as file.
  3. Give the .as file a fileName of: Root.as
  4. Copy the code from below and paste it into the the Root.as file
  5. Make sure you save the Root.as file.
  6. In the FLA you created write this: trace(”from the Root class: ” + Root.myVariable);
  7. Publish and your Output panel should say: from the Root class: some value

Here’s the code for the Root class:

This is the first step into a much larger world. From anywhere in your FLA you can access the variables in your Root class just as you did with _root before. But now your variables are in a different file and easier to locate.

Lets go over this class file real quick.

  • The public static var is just what you put before each and every variable - variables are called properties in a class.
  • The :String or :Number are how you type your properties. You don’t have to do that but you really, REALLY should. Trust me on this. Just get used to it.
  • It is a convention, and one you need to follow, to make all class names start with a capital letter. So don’t make a class name such as myClass. It should be MyClass.

A few gotchas

Very, very important: the fileName of the class file and the name of the class must be identical. Except the class name does not get the .as extension. So if the filename of your class file is SomeClassName.as then the name of the class must be SomeClassName. If you named the class SomeClassname - lowercase n - it wouldn’t work.

I’ll tell you right now, this above issue gets me all the time. The problem is that you usually give the file a fileName before you give the class a class name. Once you start write your code you think to yourself, “This ClassName would be more descriptive if it were called SuchAndSuch. So you change it, then forget to change the fileName and everything’s a mess. You’ll may do this a few times yourself so be on the lookout.

You know how with FLA files you can publish them anytime to see your changes without saving first? Well, you can’t do that with .as files. If you change something in your .as file you have to save that file (Ctrl + s) before you can publish the FLA to see those changes.

You do not need to upload the .as files to the server in order for the SWF to work. When you publish your FLA file, creating the SWF, it takes the code in all your .as files and wraps it up into the SWF. Now the SWF can stand on it’s own.

If you share your FLA with someone then you have to give them all the .as files as well. The FLA won’t work without them.

What’s next

You put some variables - properties - in your class file. So what about functions, called methods in a class file? That’s just as easy to do. Here’s an example added to the code above.

Lines 17-19 make up the method doSomething. If from anywhere in your FLA you typed: Root.doSomething(); you would see the Output panel display “this is code running in a method of the Root class.”. Which doesn’t do much of anything. Lets add another one that’s a little more useful.

Take a look at lines 21-25. The method average2numbers receives to arguments: a and b. It takes those two numbers and adds them together, then divides by two and then returns that result. That’s why line 21 has :Number appended. That declares the type of value that the method will return.

So back in your FLA you can say something like this:

Line #1 says, I want to create a variable, of type Number, and I want it’s value to be equal to the result that comes from sending the parameters (2,6) to the method average2numbers in the Root class. Then line #2 just traces that result to the Output panel.

This should enhance your workflow right off the bat by giving you a place to put your variables and functions to get at them faster than if you placed them on the _root of your FLA.

In part 2 you’ll learn how to make those public parts private and create getters and setters.