如何使用cfc对象的引用从另一个函数调用函数?

Tus*_*are 5 coldfusion cfwheels coldfusion-9

抱歉,这个问题短语.我无法找到更好的方式来描述它.但我的问题如下:

我有3个cfc,即settings.cfc,prices.cfc和helpers.cfc.这些cfc扩展了第4个cfc controller.cfc.helper.cfc如下:

<cfcomponent extends="Controller">
    <cffunction name="formatCurrency">
        <cfset formattedCurrency = 1 />    
        <cfreturn formattedCurrency>        
    </cffunction>
    <cffunction name="processTemplateVariables">
       <cfargument name="templateText" default="defaultText" >
       <cfset formatCurrency() />
       <cfreturn formattedCurrency >        
    </cffunction>
</cfcomponent>
Run Code Online (Sandbox Code Playgroud)

settings.cfc有一个setApplicationVariables方法,我们用它来设置应用程序级变量.在这个cfc中,我创建了一个helpers.cfc对象,并将该对象放入应用程序范围.settings.cfc如下:

<cfcomponent extends="Controller">
   <cffunction name="setApplicationVariables">    
      <cfset application.helpers = createObject("component","controllers.Helpers") />  
   </cffunction>
</cfcomponent>
Run Code Online (Sandbox Code Playgroud)

在应用程序启动时调用settings.cfc,然后创建helpers.cfc的对象并将其放入应用程序范围.

我们在controller.cfc中创建对ProcessTemplateVariables方法的引用,如下所示:

<cfcomponent extends="Wheels">
   <cfset getFormattedCurrency = application.helpers.processTemplateVariables >
</cfcomponent>
Run Code Online (Sandbox Code Playgroud)

在prices.cfc中,我们使用此引用来调用function processTemplateVariables它.但它does not call the function formatCurrency从processTemplateVariables内部调用,并抛出错误" variable formatCurrency is undefined ".

但如果我使用它application.helpers.processTemplateVariables(templateText="someText"),它的工作原理.
它也有效,当我使用cfinvoke如下:

<cfinvoke method="processTemplateVariables" component="controllers.helpers" templateText="someText" returnvariable="content">
Run Code Online (Sandbox Code Playgroud)

prices.cfc如下:

<cfcomponent extends="Controller">
    <cffunction name="index">
        <!--- does not work, throws 'the formatCurrency() variable is undefined' --->
        <cfdump var="#getFormattedCurrency("someText")#"><cfabort>
        <!--- works --->    
        <cfinvoke method="processTemplateVariables" component="controllers.helpers" templateText="someText" returnvariable="content">
        <!--- works --->
        <cfset application.helpers.processTemplateVariables("someText") />   
    </cffunction>
</cfcomponent>
Run Code Online (Sandbox Code Playgroud)

我不确定为什么使用引用不起作用.对于早先的混乱感到抱歉,但你的评论让我深入挖掘,我发现这是参考,这是罪魁祸首.有没有办法让这个工作参考,那会很酷吗?

Lei*_*igh 2

更新:

这篇博客文章(作者:Adam Cameron)有更好的描述。总结一下:

.. 它将方法从 CFC 中提取出来,因此它将在调用代码的上下文中运行,而不是在 CFC 实例中运行。根据方法中的代码,这可能重要也可能无关紧要。

在您的具体情况下,这确实很重要。该函数依赖于formatCurrency,而调用页面的“上下文”中不存在该依赖项,这就是您收到“未定义”错误的原因。


(来自评论)

是的,我很确定你不能这样做。每个函数都被编译成一个单独的类:特别是静态内部类。(如果转储不带括号的函数名称,则可以看到内部类名称#application.helpers.formatCurrency#)换句话说,它与任何特定实例(以及扩展后的其他函数)断开连接。

当您创建组件的实例时,所有函数都存储在其variables范围内。因此,当您从实例内部调用“processTemplateVariables”时,它可以通过组件的范围访问其他函数variables。当您的代码创建对该函数的引用时,您实际获得的内容与父实例完全断开连接application.helpers。因此它无法访问任何其他功能。这就是为什么你会收到“未定义”错误。