Passing on optional arguments in ActionScript 3

The other day I ran into a small problem with optional arguments in Flex. While writing my tutorial on AMFPHP and Flex I decided to create a small static class that would take care of all the boring stuff with calling AMFPHP. This class enables me to simply use AMFPHP.send(“ServiceName”, and so on).

However, writing the class I realized I wouldn’t be able to pass on the optional parameters. If I would use:

function send(anArgument:Object, ...args)

…I wouldn’t be able to send the args argument to the NetConnection.call method, because actionscript would send a “bunched up” array with all the arguments as ONE parameter to the call method, as opposed to a series of parameters, which was what I wanted.

The solution to this is using the Function.apply() method. What I did was to create an empty array and add a series of arguments I wanted to pass on to a function, create a reference to the function and then use the apply method. This is what my finished static method looks like:

public static function send(serviceFunction:String, resultHandler:Function, faultHandler:Function, ... args:*) : void
{
	trace("AMFPHP("+serviceFunction+")");
	// Create responder
	var responder:Responder = new Responder(resultHandler, faultHandler);
	// Create an array that will temporarily store all the arguments
	var collectArgs:Array = new Array;
	// Add the fixed arguments
	collectArgs.push(serviceFunction);
	collectArgs.push(responder);
	// Loop through the optional arguments and add them too
	for (var i:uint=0; i

11 thoughts on “Passing on optional arguments in ActionScript 3

    • I’ve been using AMFPHP since its “youth”, because at the beginning it was the only option I had for sending objects and arrays to and from PHP and maintaining the data format. Today there are other options, but it still works so smoothly for me, and using a wrapper that takes care of the AS-stuff I have no need to look for an alternative. Why? Do you prefer another remoting library?

  1. Pingback: Sangpil Research» Blog Archive » using …args as function to send data to amfPHP.

  2. Never thought would get the exact solution i needed .. i was trying to right a similar class and was stuck after using args directly … thanks a lot ….

  3. Awesome post – Huge thanks ! I was doing exactly the same thing (amfphp & drupal) and this had me stumped for an hour or so until I found this. Only been writing AS3 for a couple of days as I am a C++/C#/Java guy normally.

    May blog my resulting AS3 Drupal connector and publish code – so will add this blog to the code comments if thats ok.

    Thanks,
    Mark

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>