Get updates

Scott Q&A: How to use plain JavaScript in RJS templates

What’s all the fuss over RJS templates for Rails? JavaScript is not, in my opinion, the dirty/scary/tedious or otherwise lame language some people seem to think it is. I actually enjoy writing JavaScript objects, and currently the codebase of my hierarchical list manager app contains about as much JavaScript as Ruby code.

Despite my JavaScript predilection (or because of it), I am happy to work with RJS templates. Why? Because they make working with JavaScript (and client-side capabilities JavaScript offers) in Rails a whole lot easier. A lot of what makes Rails really fun is stuff like the easy integration of Ajax and JavaScript for the UI, such as Scriptaculous.

RJS templates make it a snap to respond to an Ajax request with much more than just an update for a single element, through a number of wrapper functions that generate JavaScript for you. Yet sometimes you’ll still want to interact with your own custom JavaScript functions and objects.

Question: How can plain JavaScript be used inside RJS templates?

Answer: It is quite easy, as this slide on RJS points out. All of the helper methods in RJS templates belong to the page object. Page also has a concatenation method that allows you to append your own JavaScript code, like this:

page << "emptyInput('main_input');"

As with any quoted strings, you’ll often want to escape your quotes; Rails has a helper for this, of course:

page << escape_javascript("emptyInput('main_input');")

…though this example didn’t strictly require escaping. There’s also plenty of opportunity to have Rails evaluate expressions and substitute variables:

page << "enter('#{ @list_item.parent_id.nil? ? 'main_list' : (@list_item.parent_id.to_s << 'c') }');"

All of this is, of course, in addition to the built-in methods RJS provides for free, which may be a topic for another time.

Leave a Reply

Fatal error: Call to undefined function show_subscription_checkbox() in /home/dmetro/ on line 90