Forwarding a dynamic argument “…(rest)” array in Flex
If you’ve done much in flex, you may have used the “…” notation in a method signature to indicate that the function takes a dynamic number of arguments, such as:
private function doIt( ...args ):void
… then called the method:
doIt( 1 ) doIt( 1, 2 ) doIt( "some", "other", "stuff" )
The question is this: from within that method, how do you send those same arguments on to another method that accepts a dynamic argument array? You can’t just pass the “args” array, as the method called will only see 1 argument; the array you passed it. Instead, you need to “explode” the array into its’ original parts. Here’s the most simple way I’ve found to forward that array on to the next method:
public function doIt( ...args ):void
{
var someObject:SomeType = new SomeType()
someObject.someMethod.apply( someObject, args );
}
The “apply” method of Function does exactly what we need. Now “someMethod” will have it’s own argument array, and be able to access them the same way you were able to from within “doIt”.
This all came about when we began writing a wrapper of sorts for WebServices. We created our own RPC class, with a “call” method that accepts the parameters, and we needed to forward them on to Operation’s “send” method. Below is a much simplified example:
import mx.rpc.soap.Operation;
public class RPC
{
public static function call( operation, ...params ):void
{
//...code to initialize WebService "svc"
var op:Operation = Operation( svc.getOperation(operation) );
//...more code (unimportant)
var token:AsyncToken = op.send.apply( op, params );
//...code to hook up handlers
}
}