About
The official blog of Team Mach-II and is the best place to stay up to date on all things Mach-II.
Categories
copyToScope - Yet another Wicked Mach-II Feature!
Fine, I'm biased - I'll admit it! But when you have features like copyToScope(), it's hard not to be. If you've come to Mach-II from a non-MVC background, it's likely you've found that the views in your Mach-II applications have considerably less logic than many traditional ColdFusion templates.
With that said, it's impossible to abstract all the logic from your views, as you typically need to have some <cfif>'s, <cfloop>'s, and <cfset>'s to output your data to the user.
One recurring theme you may have noticed in your own Mach-II applications are a chunk of <cfset> tags at the top of your views. They might look something like this...
<cfset user = event.getArg("user") />
<cfset result = event.getArg("result") />
<cfset products = event.getArg("products") />
<cfset imagePath = getProperty("imagePath") />
As you can tell, extracting specific variables from the event object and application properties set often leads to a lot of bulky boilerplate code at the top of your views. No fun! This is where the copyToScope() method comes in. Conveniently, copyToScope() is automatically made available to you for use within any view in Mach-II as the newest member of the handy ViewContext.cfc. So, reworking our example above, all we need to do is use Mach-II's simple expression syntax and pass our variable assignment string to the copyToScope method, like so:
<cfset copyToScope("${event.user},${event.result},${event.products},${properties.imagePath}") />
By default, this command will automatically create variables for use on your page with the same name as the event arguments or application properties. However, we can also easily assign the results of the expression evaluation to a different variable name:
<cfset copyToScope("u=${event.user}") />
In this case, the user object is placed in a variable called "u" rather than "user". Also, we can assign default values to our page variables like so:
<cfset copyToScope("img=${properties.imagePath:'default/image/path'}") />
But wait! There's more! Say we want to get at some data nested in an object:
<cfset copyToScope("${event.user.fullName:'Jay Leno'}") />
Assuming you have a getFullName() method in your user object, this syntax will actually grab the full name using the getter method from the user object automatically. Pretty cool, huh? The point is, the copyToScope method really cleans up your views, and can turn ten bulky lines into 1 effortlessly. For more info on copyToScope(), check out our wiki article. Have fun, and post a comment on the blog to let us know how many lines you save!
2 Comments
|
0 Trackbacks
|
Mach-II 1.8 |
Send
Posted 6/11/09
@ 2:09 PM by Brian FitzGerald
Comments
just want to add acomment
Posted by wow gold at 2/6/10 12:49 AM
very happy to comment here
Posted by replica watches at 2/6/10 12:50 AM
