Last updated by BrandonFranklin 7 years ago

Dynamic Javascript Plugin

Generate javascript from controllers in response to AJAX requests, similar to Rails RJS Templates.

Blog entry:

The plugin:

Simple Demo App:


What I have now looks like:

renderJavascript {
  replace 'user_list'
  effect 'highlight', "user_list"
It adds two methods to all controllers: boolean isAJAX() and renderJavascript(). The basic methods supported are:


appendJavascript "alert('hi')"


callFunction "foo", 1, true, [a,b]
will generate:
foo(1, true, [a,b]);
JSON encoding is used for the arguments.


effect 'appear', 'element_id', [delay:3]
will generate:
new Effect.Appear('element_id',{'delay':3});

update and replace

These methods use the grails render method, supplying it with an out option. If you don't supply an template option, the element id will be used by default. The rendered template is javascript encoded and used in a prototype update or replace call.

update 'document_1', [text:'Hello']
replace 'document_list'
will generate:
Element.replace('document_list',  <render _document_list.gsp> );


Queue up some actions at the end of the scriptaculous effects queue.

     callFunction "c"
will generate:
new Effect.Event({ afterFinish:function() {
}, queue: "end" });
For an example of this, see the demo app - when deleting, it fades out the deleted row, and then queues up a call to remove the <tr> dom element and recolor alternate table rows.

Demo App

I've made a simple demo application based on a scaffolded 'Book' controller. I've changed the grails-generated controllers and views to use AJAX calls for creating and deleting books using the plugin.

Security Delimiters

The plugin adds security comment delimiters (see this pdf on javascript hijacking linked to from Prototype). Because of this, it needs Prototype 1.6.0rc0 or later. (To use a different version of prototype, go and comment/delete the line DynamicJavascriptGrailsPlugin.groovy:36

javascript = "/*-secure-*n"+javascript+"/"

Things that I may implement if I need them:

  • 'GJS' templates - stick the javascript generating code into a separate view file
  • Helpers for testing dynamic javascript
  • Render an entire view and extract certain elements by id, only updating those ones.
  • Access to more of the prototype library - e.g. inserting content, selectors and iterations:'#items li').each do |value|
# => $$('#items li').each(function(value) { value.hide(); });