views:

267

answers:

2

In Flex, you can add functions to the prototype of a Class; but how do you add a setter?

For example, with A some (non-dynamic) class, you can do this:

var o:Object = new A();
A.prototype.myFunction = function():void{trace("foo");}
o.foo();

And that will call the foo function. But how could you add a setter, so that setting the property calls the setter (just like it would if you declared the setter in the "normal" way on the A class). So what I want is something like this:

// doesn't work!    
A.prototype["set myProperty"] = mySetter; 
o.myProperty = "test"; // should call mySetter

PS: Manipulating the prototype is an unusual thing to do in Flex, and not something I'd recommend in general. But for the sake of this question, just assume that there is a reason to dynamically add a setter.

+2  A: 

ActionScript 1/2 supported this by calling addProperty(name, getter, setter). This could be done on individual objects or on a prototype. AS3 doesn't support this, even with the "-es" flag.

For reference, here's an example of how it used to be done:

var A = function() {};

A.prototype.addProperty("myProp", 
    function() { 
        trace("myProp getter: " + this._myProp); 
        return this._myProp; 
    }, 
    function(value) {
        trace("myProp setter: " + value); 
        this._myProp = value; 
    });

var a = new A();
a.myProp = "testing";
var x = a.myProp;
Sam
A: 

As far as I know, there is no way to use the old prototyping methodology for getters/setters (infact, I believe the grand total of internal flex sdk classes that use any type of prototyping is 0).

In any case, getters/setters aren't available in the prototype-hacking game. Even if there were, I would imagine that there is a better alternative to that which you are trying to acomplish which would play with flashPlayer's architecture a tad better. My 2p.

jeremym
This is not true: "getters/setters aren't available in the prototype-hacking game". getters/setters have been in use since at least Flash 5 and probably sooner, long before AS3 classes (AS2 classes were just syntactic sugar and compiled down to prototype usage).
Sam