Over on Peter Bell's blog he wrote the article that I was going to write on The Benefits of Named Arguments When Calling CFC Methods, thus saving me the trouble (Thanks Peter). However, I would like to add another interesting way to use them, and that's the topic of this post.
Let's say that you're doing something cool like a form generator, and you don't want to spec out the form using XML and define yet another form definition language. You'd like to do it functionally, but any form tag like, say, "input" has dozens of attributes that the developer may or may not want to use, which makes using default arguments and positional placement problematic.
The answer? Named arguments. Check out the following:
f=createObject("component","formGenerator");
f.input(label='Name', name='name', style="font-weight:bold");
f.input(label='Address', name='address');
...
As you can see, other than the initial "f." and the commas between the arguments the function looks and behaves almost exactly like the standard input tag, with all of the attributes you'd normally expect, plus a few more (like label) for added functionality.
Now here's the code I mentioned earlier that processes these arguments:
<cffunction name="input">
<cfargument name="name" type="string">
<cfscript>
for (attr in arguments)
{
switch (attr)
{
case 'name':
// special case name
break;
case 'label':
// special case label
break;
default:
// not interested, pass through
passthrough(attr,arguments[attr]);
break;
}
}
</cfscript>
</cffunction>
Notice how we handle the tag attributes that have special meaning to us like label and name, but simply pass through any other values (like style) that we don't care to define. Also note we've defined one parameter that we must have (the field name) but all of the others are optional.
And should a future version of HTML specify a new attribute for input, the code will simply pass it on to the browser.
All in all, a very useful technique to have hidden away in your toolbox.
Good stuff Michael. I like to use it in this way too (though, for more than scripting forms, as I'm sure you do too!)
Posted by: Sammy Larbi | May 14, 2007 at 08:35 AM
@Sammy, I've found I've gone from code definitions to XML definitions and back to code again. CF is not Java.
Posted by: Michael Long | May 14, 2007 at 08:45 AM