JavaScript Generation

WebDialogs require a substantial amount of JavaScript code. Although there are some common patterns (eg, handle a button click), any given plugin will only need a subset of these, possibly with minor variations.

I don't want to wade through unused code while debugging; any JavaScript code in the client should be there for a reason. Nor do I want to copy and paste (let alone edit and maintain) tons of repetitive code for each plugin I write. So, I use dynamic JavaScript generation (ie, home brew macro pre-processing) via the Dialog Framework.

Each *.js.erb file, which gets processed into a *.js file, contains calls to JavaScript generation methods, written in Ruby. Each call requests a snippet of code, possibly using parameters to customize the result:

  j2r_setup   = @js.j2r_setup('do_cb') +

  pf_prefix   = @js.pf_prefix
  pf_suffix   = @js.pf_suffix

  out = eval @pf.indent(<<-'EOT')
  function() {
    #{ pf_prefix }
    #{ j2r_setup }
    #{ pf_suffix }

The PF_Gen_JS class, referenced above via @js, generates the necessary JavaScript code via Ruby methods. Each Ruby method is free to take advantage of Ruby's capabilities (eg, argument list trickery, conditionals, here documents, string substitution), as long as it returns a string containing valid JavaScript code.

This code is then incorporated into *.js files by means of Embedded Ruby. DF's code indentation support (eg, @pf.indent) allows the output to be indented in a consistent and controllable manner.

Every part of the code (the PF_Gen_JS class definition, the *.js.erb files, and the resulting JavaScript code) can be kept as clean and readable as desired. And, of course, the generated *.js files contains only the needed JavaScript code.

This wiki page is maintained by Rich Morin, an independent consultant specializing in software design, development, and documentation. Please feel free to email comments, inquiries, suggestions, etc!

Topic revision: r6 - 02 Jan 2012, RichMorin
This site is powered by Foswiki Copyright © by the contributing authors. All material on this wiki is the property of the contributing authors.
Foswiki version v2.1.6, Release Foswiki-2.1.6, Plugin API version 2.4
Ideas, requests, problems regarding CFCL Wiki? Send us email