Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method dynamically with unknown number of arguments in flash AS3?

I have an object MyTester, that has an instance of another class MyClass, and I want to test MyClass API through it:

public class MyTester {
   internal var myObj:MyClass;

   public function MyTester() {
        this.myObj  = new MyClass(); 

        trace(this.MyClassTestAPI("Foo", "arg1", arg2)); // tests function Foo(arg1:String, arg2:Number):String
        trace(this.MyClassTestAPI("MyProperty"));  // tests function get MyProperty():String
        trace(this.MyClassTestAPI("MyProperty", "new value"));// tests function set MyProperty(val:String):void
   }

   public function MyClassTestAPI(functionName:String, ...rest):* {
        var value:*;            
        try {
            if (typeof(this.mediaPlayer[functionName]) == 'function') {
                switch(rest.length) {
                    case 0:
                        value = myObj[functionName].call(functionName);
                        break;
                    case 1:
                        value = myObj[functionName].call(functionName, rest[0]);
                        break;
                    case 2:
                        value = myObj[functionName].call(functionName, rest[0],rest[1]);
                        break;
                    default:
                        throw("Cannot pass more than 2 parameters (passed " + rest.length + ")");
                }                
            }  else {
                switch(rest.length) {
                    case 0:
                        value = myObj[functionName];
                        break;
                    case 1:
                        myObj[functionName] = rest[0];
                        break;
                    default:
                        throw("Cannot pass parameter to getter or more than one parameter to setter (passed " + rest.length + ")");
               }                
            }
        } 
        return value;                
    }
}

How can I cancel the switch and make it work for any number of arguments? Thanks!

like image 483
Gil Avatar asked Jul 06 '11 07:07

Gil


1 Answers

Use the Function.apply() method. It's kind of the same as call but you pass the parameters as an Array. Something like:

function doCall( callback:Function, ... args ):void
{
    // args is now an array
    callback.apply( null, args );
}


// call it like this
this.doCall( this._myFunc1, 1.0 );
this.doCall( this._myFunc2, 1.0, 2.0 );
this.doCall( this._myFunc3, 1.0, 2.0, "hello" );

// to call these functions
private function _myFunc1( num:Number ):void {}
private function _myFunc2( num:Number, num2:Number ):void {}
private function _myFunc3( num:Number, num2:Number, msg:String ):void {}

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()

like image 186
divillysausages Avatar answered Nov 12 '22 18:11

divillysausages