Search code examples
coldfusionmura

How to access predefined variables within cfscript?


The following code works:

<cfoutput>#$.currentURL()#</cfoutput>

However, within a function, "$" is not available.

<cfscript>
function myTest() {
  return $.currentURL();
}
</cfscript>

Does anyone know what actually is the equivalent of $ within a function?

Likewise, #pluginConfig.getDirectory()# works when used directly in cfoutput. However, within a cfscript function, it reports "unknown variable pluginConfig."

Thank you for advance for guiding me in the right direction.


Solution

  • When writing code outside the Mura Event Scope (like you do with that function), you have to obtain an instance of the Mura Scope ($) yourself. This can be done using the following code:

    $ = application.serviceFactory.getBean('$');
    

    Next you'll have to initialise the instance using an event object, a struct with value pairs or a 'siteID':

    $.init(event);
    $.init(myStruct);
    $.init(siteID);
    

    The same counts for the pluginConfig, this you can abtain via the Mura Scope. You'll have to pass the pluginID, moduleID, name or package of the plugin:

    $.getPlugin(pluginID);
    $.getPlugin(moduleID);
    $.getPlugin(name);
    $.getPlugin(package);
    

    An other option you have is to pass the Mura Scope and the pluginConfig as arguments to the function. When writing a small plugin, this might be the easier way. But when writting medium or large plugins, it will get a bit messy when you're passing along these objects all the time.