Using components directly in CFScript and CFML



You can invoke methods of a component instance directly using CFScript or in CFML tags. To invoke component methods directly, use the CreateObject function or cfobject tag to instantiate the component. Thereafter, use the instance name followed by a period and the method that you are calling to invoke an instance of the method. Always use parentheses after the method name, even if the method does not take any parameters.

You can use this syntax anywhere that you can use a ColdFusion function, such as in cfset tags or surrounded by number signs in the body of a cfoutput tag.

Invoking component methods in CFScript

The following example shows how to invoke component methods in CFScript:

<!--- Instantiate once and reuse the instance.---> 
<cfscript> 
    tellTimeObj=CreateObject("component","tellTime"); 
    WriteOutput("Server's Local Time: " & tellTimeObj.getLocalTime()); 
    WriteOutput("<br> Calculated UTC Time: " & tellTimeObj.getUTCTime()); 
</cfscript>

In the example, the three CFScript statements do the following:

  1. The CreateObject function instantiates the tellTime CFC as tellTimeObj.

  2. The first WriteOutput function displays text followed by the results returned by the getLocalTime method of the tellTimeObj instance.

  3. The second WriteOutput function displays text followed by the results returned by the getUTCTime method of the tellTimeObj instance.

In CFScript, you use the method name in standard function syntax, such as methodName().

Invoking component methods in CFML

The following example uses CFML tags to produce the same results as the CFScript example:

<cfobject name="tellTimeObj" component="tellTime"> 
<cfoutput> 
    Server's Local Time: #tellTimeObj.getLocalTime()#<br> 
    Calculated UTC Time: #tellTimeObj.getUTCTime()# 
</cfoutput>

Accessing component data directly

You can access data in the component’s This scope directly in CFScript and cfset assignment statements. For example, if a user data CFC has a This.lastUpdated property, you could have code such as the following:

<cfobject name="userDataCFC" component="userData"> 
<cfif DateDiff("d", userDataCFC.lastUpdated, Now()) GT 30> 
    <!--- Code to deal with older data goes here. ---> 
</cfif>

For more information, see The This scope.