Using ColdFusion for Dynamic Server-side JavaScript

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:

<cfparam name="url.year" default="#year(Now)#">
...
<script type="text/javascript" src="/ClientIncludes/DynamicCFJS.cfm?year=#url.year#"></script>

You could then have in your DynanicCFJS.cfm something like this:

<cfsetting enablecfoutputonly="yes" showdebugoutput="no">
<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.

TrackBacks
There are no trackbacks for this entry.

Trackback URL for this entry:
http://www.brianmeloche.com/blog/trackback.cfm?B80A220E-3048-2E57-0AB20EBE9FFFC4D4

Comments
I prefer your method. If for no other reason than because it discourages any future developer from adding anything between the two lines (as they could with the other method).

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.
# Posted By dave | 4/22/08 7:04 PM
constructors in other languages return something... but it's built into the language:

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.
# Posted By dross | 4/22/08 7:05 PM
# Posted By palm tree lamp | 8/19/08 3:04 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.5.002.