Version 1 (modified by cfgrok, 16 years ago)

Renamed page for alpha sorting on home page

Event.copyToScope()

This feature makes it easier to pull variables out of the event scope and place them into another scope.

Say you want to pull 3 values from the event and use them in your view. Normally, you would run 3 separate commands:

    <cfset foot = event.getValue("foot") />
    <cfset hand = event.getValue("hand") />
    <cfset xe.nested = event.getValue("xe.nested") />

the end result being that each value: foot,hand,xe.nested is now in the variables scope ready for use in your view.

Here in the labs of Model-Glue, we want to reduce developer excise when possible. The new copyToScope() method can be used to short cut the same process.

    <cfset event.copyToScope(variables, "foot,hand,xe.nested") />

The end result is the exact same as above, except only 1 line of code is needed to pull several values from the event at once.

What about default values?

As event.getValue() takes an optional argument to set default values, our new friend event.copyToScope() will take an optional array of default values. The position of the list elements pertain to the position of the value in the array. This means the 1st value in the list gets the 1st position in the array, the 2nd gets the 2nd and so on. Let's look at an example where I want to provide defaults to 2 items in the list:

    <cfset defaultArray = ["DefaultForFoot", "DefaultForHand"] />
    <cfset event.copyToScope(variables, "foot,hand,xe.nested", defaultArray) />

Once the function executes, the value of variables.foot is DefaultForFoot and the value for variables.hand is DefaultForHand. If no value existed in the event for xe.nested, it will be set to an empty string as per normal when a value is requested from the event that has not been set yet.

Does it only work with the variables scope?

Nope. It will work with any scope you see fit. Session, Server, Application, even a plain ole struct, though I expect the variables scope will be most often used.