Feb
12Using ColdFusion for Dynamic Server-side JavaScript
Posted By: Brian Meloche; Posted At : February 12, 2007 3:08 PM
Related Categories: ColdFusion, JavaScript, AJAX
Here's a little tip for using a .cfm file for dynamic JavaScript generation.
Need to use JavaScript, but not sure what the JS will actually look like until you build it... but don't want to show the JavaScript on the webpage? I am using Spry for some Ajax style selects, but I need to control the XML on the fly.
Try something like this:
...
<script type="text/javascript" src="/ClientIncludes/DynamicCFJS.cfm?year=#url.year#"></script>
You could then have in your DynanicCFJS.cfm something like this:
<cfoutput>
var dsYears = new Spry.Data.XMLDataSet("/index.cfm?event=buildYearList&year=#url.year#", "carlineYears/year", { useCache: true });
</cfoutput>
Of course, similar techniques will work in any web language. Tailor to the web language of your choice.


If you intend that init() should be called upon instantiation, every time, then write your code to reflect that.
Your method (which I use as well) ensures that no-one will try to use the component before it is fully intialized and allows all other code in that component to assume that init() has been run.
Class myClass = new Class();
The "new" keyword assigns the instance.
In CF we make our own constructors. Any CF developer not using an init() with <cfreturn this/> is violating best practices and would have a very difficult time convincing me why going against them is a good idea. Frameworks like ColdSpring rely on the fact that developers adhere to best practices... if you have a CFC with an init() method that doesn't return itself it would be incompatible with ColdSpring.