Eureka!
I’ve been having a lot of trouble having Event (clicks, loads, whatever…) in Flash for as long as I’ve been doing Object oriented ActionScript. I barely managed to call inline functions and having to use the absolute path to the property. Example:
class Foo {
public var _someProperty:String
public function Foo() {
// Lets skip how I actually make the button,
// but I usually use .attach() and I make
// exportable the object in the Library. I
// think I should use createClassComponent however.
var but:MovieClip = new MovieClip();
but.onPress = function () {
_root.MyFooObject._someProperty = “Clicked”;
}
}
}
To access my attribute, I must leave my class and follow the absolute, pratically hard-coded path to my value. It’s really not a good thing to do. I found you can use the Delegate class to forward events to a function inside the parent class. Like this:
class Foo {
private var _someProperty:String
public function Foo() {
// Lets skip how I actually make the button here too.
var but:MovieClip = new movieclip();
but.onPress = mx.utils.Delegate.create(this, button_onClick);
}
private function button_onClick():Void {
this._someProperty = “Clicked”;
}
}
Where “this” means the class you are in (could be another one), and “button_onClick” is the name of the function you will be calling after the event is triggered.
There you go! It’s a lot more powerful, much more logical in a semantic point of view and it makes the code a lot clearer. Notice how I can protect my call properties now using the private attribute.
Speaking of being semantic, you always should call you call properties with “getters and setters” instead of calling it directly like I did in my example. It should look like this instead:
private var _someProperty:String
public function get someProperty():String { return this._someProperty;}
public function set someProperty(val:String):Void { // validation if needed; this._someProperty = val;}
What still needs to be clarified however is how I can pass the object that raised the event and called the function.