shake, with fries

by Zach Carter

Unobtrusive JavaScript in Rails 3

One of the coolest features I've heard about the upcoming Rails version 3 is its support for unobtrusive JavaScript.

The current JavaScript helpers in Rails produce HTML littered with in-line Prototype specific code:

<a href="#" onclick="new Ajax.Request('/comments/1', {asynchronous:true, evalScripts:ture, method:'delete'}); return false;">Destroy</a>

The new technique instead adds hooks in the form of HTML5 data attributes to the markup:

<a href="/comments/1" data-remote="true" data-method="delete">Destroy</a>

While unobtrusive, this particular example provided by DHH is still not degradable, but that's another issue (use button_to instead of link_to for deletes.)

I currently use a technique similar to data attributes, but utilizing the class attribute:

<a href="/comments/1" class="remote delete">Destroy</a>

And in my jQuery code, I can identify the element by its class name and dispatch the appropriate event handlers:

$('a.remote').click( /* click handler */ )

The click handler would use the href attribute and delete class name to know where and how to send the request.

This works well for hand crafted unobtrusive scripts, but you wouldn't want your framework overloading class names with arbitrary data, as it may conflict with stylesheet rules, and, it's kind of an abuse of the class attribute anyway. Using a future compatible HTML attribute is a nice solution. If you're worried about validation, you could always switch to the HTML5 doctype.

Since the scripts have been (rightfully) separated from the content, it also becomes much easier to switch out JS frameworks and still be able to use the built in Rails helpers. Cheers to this change!

rails javascript html5 | May 23, 2009 at 4:39 PM

Short url: http://zaa.ch/24

blog comments powered by Disqus