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
Was trying to do the exact same thing got stuck found this … BEAUTIFUL!!! Thanks a million
Awesome, thanks for the example!
Hi! I was surfing and found your blog post… nice! I love your blog.
Cheers! Sandra. R.
Excellent! I really couldn’t think of this by myself
Thanks for your help!
Are you using amfphp?? Is it good? Why do you want to use amfphp??
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?
Amazing, really awesome issue. I will blog about it also.
Pingback: Sangpil Research» Blog Archive » using …args as function to send data to amfPHP.
Thanks dude. Just what I was looking for.
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 ….
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