views:

32

answers:

1

i've never tried to do this before, so my head a swimming a bit. i'd like to have a public boolean called enabled in myClass custom class. if it's called to be changed, how do i trigger a function from the change?

should i add an Event.CHANGE event listener to my variable? can i do that? or is there a more standard way?

+2  A: 

We usually use properties for that.
Properties are just like public variables for the outside -- you can set instance.enabled = true; and so forth.. But you define properties as getters and/or setters functions for the class.
They are the perfect place for custom logic to be executed on value changes.

For example:

public class CustomClass {
    private var _enabled:Boolean = false;

    public function set enabled(value:Boolean):void {
        trace('CustomClass.enabled is now', value);
        this._enabled = value;
    }

    public function get enabled():Boolean {
        trace('CustomClass.enabled was retrieved');
        return this._enabled;
    }
}

Note that they can't have the same name as your private variable and you don't need both of them defined. Actually, you don't even need a variable for a setter/getter. You could use them just like any function -- they just supply you with a different syntax.
For example:

var object:CustomClass = new CustomClass();
object.enabled = false;
if (object.enabled) {
    ...
}

They are great to expose a simple API, keeping you from rewriting outside code if the class' internals have to change.

AS3 Reference on getters and setters.

MrKishi
Wouldn't he want something that calls a function on a property change such that that when object's enabled is changed (dynamically?) something listens for the change ?
phwd
If so, I misunterstood what he meant.
MrKishi
well, it is possible to make the setter function call or actually include code that would handle the change based on the new set value. is this the code format AS3 APIs use so we can call properties like mySprite.alpha = 0.5, or myTextField.enabled = true?
TheDarkInI1978
yes, this is what i'm looking for. thanks.
TheDarkInI1978
Yeah, and that's why you can override them -- another advantage of properties. And if you need the CHANGE event for the outside, you could still implement the EventDispatcher interface and dispatch an event from the setter... Simply enough.
MrKishi