Travels

Thursday, October 25, 2007

The Delegate Class: Brother where have you been?

Eureka! I've had a specific problem when writing AS2 classes for some while now. Namely, whenever I use code to make an interactive element (Let's say a movie clip that bounces away when you click on it), I have to nest the event handler's method. The problem is that this changes the scope and so the handler method can't access my classes base methods. The way I used to fix this was by making the methods I want to access Static, and accessible by anything in my class. The problem with this is that if I make a method static I have to make its variables static, and that can create a domino effect of making things static just to solve the original problem. This is pretty wordy so I'll post code that is easier to follow. Here's the old way I did things:

class SomeClass {
//constructor
public function SomeClass(someMC) {
//initialize object
initialize(someMC);
}
//this is static so the onPress method can access it
private static function doSomething() {
trace("Ok, I'm doing something");
}
private function initialize(someMC) {
trace(someMC);
//define what it needs to do when it loads
someMC.onPress = function(){
doSomething();
}
}
}

This is a very simple version of the problem. In reality the method my handler calls would probably be called by other methods and use variables that all would need to be made static. I knew this was not a good way to do things but until now I didn't know what else I could do.

Thanks to the Delegate class though, I'm able to specify the scope and therefore access the methods at my class' base level. Here's the same code as above but made with the delegate class:

//import the Delegate class
import mx.utils.Delegate;
class SomeClass{
//constructor
public function SomeClass(someMC) {
//initialize object
initialize(someMC);
}
private function pressHandler() {
trace("You pressed it.");
}
private function initialize(someMC) {
//define what it needs to do when it loads
someMC.onPress = Delegate.create(this, pressHandler);
}
}

Now there is no need for static so things are much easier when I need to tweak things later on.
While I was researching how to solve this problem I found other possible solutions but this was the one I understood best and was able to easily implement.

You can read all about the Delegate Class here: http://www.actionscript.org/resources/articles/205/1/The-Delegate-Class/Page1.html

This is all great to know but this problem has been resolved in Actionscript 3 thanks to its addEventListener method. Still if you're using on Flash Lite or like me your work doesn't want you to use AS3 until the Flash PLayer 9 adoption rate is higher you may find this very useful.

Good luck using the Delegate Class, and if you have other solutions I'd love to see what you have come up with.

No comments: