Home > Flex 4 Examples > Passing the rest parameter

Passing the rest parameter

As you probably know, you can create a function where the last parameter is a “…rest” variable.

You probably also know that when inside the function, the comma delimited variables from the caller show up as an array. This is unfortunate when you want to pass the set of values through to another function.

Enter the apply function. What this means is that you can take the array that just came in and pass the parameters off to another function in the same manner it came in, as long as it isn’t a constructor. Adobe has deferred that until later.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:mx="library://ns.adobe.com/flex/halo"
			   minWidth="1024" minHeight="768"
			   creationComplete="application1_creationCompleteHandler(event)">

	<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			import mx.utils.ObjectUtil;
			
			protected function application1_creationCompleteHandler(event:FlexEvent):void
			{
				one("this", "is", "a", "set", "of", "parameters");
			}
			
			private function one(...parameters):void
			{
				//Bummer, I can't send parameters down to two as it came in...
				two(parameters);
				
				//Or can I ?
				two.apply(this, parameters);
				
				//You can of course manipulate the rest parameter before passing it on...
				parameters.unshift(parameters.shift(), "really");
				
				two.apply(this, parameters);
			}
			
			private function two(...parameters):void
			{
				trace( ObjectUtil.toString(parameters) );
			}

		]]>
	</fx:Script>
</s:Application>
Advertisements
  1. abner
    June 18, 2010 at 10:12 AM

    great post man… thx a lot!!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: