Unobtrusive, yet explicit

Send to friend

A few weeks ago I started a new side project (a string-figure catalog, not yet ready for an audience, sadly), and I figured it would be a good opportunity to dabble in the new goodies in Rails 3. It’s been a fun experience, for the most part, but I’ll save my “wins and fails” for a separate post.

For now, I want to focus on one particular frustration: Unobtrusive Javascript (UJS). In any project of even moderate complexity, I’ve found that Javascript plays a role, and in Rails 2 the primary way to play that game was by inlining your Javascript. (This is where you put Javascript directly into your tags, for instance in “onchange” or “onclick” handlers.)
Apparently this is a Bad Thing, although the only arguments I’ve found against inline Javascript sound suspiciously like “purity for purity’s sake”. At any rate, Rails 3 is embracing UJS, and you’ll find that helper methods like “link_to_function” don’t even exist in Rails 3.

This raises the question: what do you do instead? Well, you have to use UJS. Only, UJS in Rails isn’t super mature yet; there’s a lot of manual labor involved simply trying to work around the absence of “link_to_function”.

So, I set to work. Initially, I tried to copy what rails.js was doing (for Ajax operations, etc.): I installed a handler, and examined the triggering element to see what operations match:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

document.observe("dom:loaded", function() {
$(document.body).observe("click", function(event) {
var element = event.findElement("a[data-toggle]");
if(element) {
var action = element.readAttribute("data-toggle");
element.hide();
element.next().show();
event.stop();
} else {
var element = event.element();
if(!element.readAttribute("data-tab")) element = element.up("a[data-tab]")
if(element) {
selectTab(element.readAttribute("data-tab"));
}
}
});
});

I quickly realized that this does not scale, for two reasons. The first is that you quickly wind up with a massive branch statement inside each of your observer functions, with finicky conditions that (hopefully) map to actual elements in your views. The second is that the relationship between your markup and your Javascript is tenuous at best; even coming back to my code just a few days later, I found it was challenging to discover what code was executed when a link was clicked.

This is, I believe, one of the greatest strengths of inline Javascript: the relationship between markup and code is immediately obvious, and it requires very little hunting to follow the path of execution from the inception of an event.

So I went looking at what other options exist. Low Pro, an extension to Prototype for aiding with UJS, looked promising; I liked how each behavior was registered separately, which seemed like it would give a stronger relationship between markup and execution. However, Low Pro uses CSS selectors to identify which markup gets associated with which callbacks, and while this sounds like it ought to be a great idea, it falls down for one really big reason: CSS selectors depend on styling attributes (classes and ids), and trying to tie functionality to those means you are still left staring at markup and wondering where all the events go. Sometimes a class is stylistic, and sometimes it is logical, and there is not generally any clear way to determine which is which.

Now, you could resort to naming conventions: if a class name is prefixed with “behavior-” (or similar), then it refers to a behavior that is defined in Javascript. That’s closer to what I was looking for, so I played with that.

But what I soon discovered was that you wind up with a bunch of CSS classes that are not used for styling at all, because they specifically refer to dynamic behaviors. What I really wanted was an altogether different attribute for specifying behaviors, like what “onchange” and “onclick” gave me before. Only I had to beware upsetting the Manifold Avatars of UJS Purity by embedding actual Javascript.

What I finally ended up doing (I’ll say I “stumbled on it”, rather than “invented it”, since I’m positive it’s been done before) was defining a “data-behaviors” attribute on every element that needed one:

<%= link_to "Add an alias", "#", "data-behaviors" => "add-alias" %>

Then, in my Javascript driver, I registered callbacks for those named behaviors:

1
2
3

Behaviors.add("click", "add-alias", function(element) {
// ...
});

The result is UJS that clearly reveals the relationship between the markup and the code; you can easily search for all elements in the views that behave like “add-alias”, for instance, and given a behavior name (like “add-alias”), you can quickly find the code that gets executed for it. Elements can have multiple behaviors, too: just give a space-delimited list of behavior names in the “data-behaviors” attribute.

It’s not perfect, though: the current implementation doesn’t deal well with elements that want to behave like X on “click”, but Y on “change”. That’s not a scenario I’ve needed to deal with yet, though, so I’m sure when (if?) it comes up, a solution can be found. In the meantime, I’m quite pleased with this. It “clicks”, whereas other UJS solutions just felt obscure and heavy-weight.

Below is the code for behaviors.js. Please feel free to fork the gist on Github and hack away; I’m sure it can be improved upon in lots of ways.

Enjoy!

Update: Josh Peek suggested some tips that resulted in a drastic simplification of behaviors.js. It’s simple enough now that there’s almost no point in providing it as a separate library!

Images: