Skip to content
Judson edited this page Jun 30, 2011 · 1 revision

The Unobtrusive Ideal

Unobtrusive scripting is an instance of the concept of Separation of Concerns. Javascript's role in a webpage is properly the definition of the way the page behaves, just the way that the markup describes its structure.
The way that HTML uses Javascript though is problematic. The use of attributes to tie scripts to elements couples HTML and Javscript very tightly. We haven't put "style" attributes in our HTML since 1998, so why do we still use "onclick"?

One benefit of separating behavior from structure is that if you put all your behavior in one place, you'll know where to look when you're trying to figure out why it doesn't work. Having your behavior laid out in one file gives you one place to go to change it, which is a huge time savings.

Plus, UJS can make it easier to build your site such that it'll work for those benighted souls who don't have Javascript enabled or available. You simply write your Javascript such that it interacts HTML that doesn't require the Javascript to run, and if Javascript isn't avaiable in the client, it runs fine.

Why is NinjaScript useful? Why do I care?

We take the awesomeness of CSS for granted. In CSS, when you apply a style to a selector, it always works and always applies to matching DOM nodes - no matter when those nodes were created.

JS does not work this way: if you attach event handlers to nodes matching '.i_am_cool' now, future i_am_cool nodes won't necessarily get those handlers.
We can fix handlers with event delegation (as in jQuery).

That works fine for event handlers, but it can't help you when your Javascript needs to make changes to the document being displayed to the user. This is increasingly important when you want your Javascript to degrade gracefully, since you often want the pre-Javascript HTML to look one way, but have the Javascript modify it when it loads.

Suppose, for example, we want to unobtrusively add structure to some divs (i.e. rounded corners) or replace one element with another (convert forms to links or other behavior). These transformations will get run once when our script executes, and won't happen automatically to future matching elements.

NinjaScript allows you to specify behaviors - including transformations - and attach them to selectors once, and then count on them always applying to any future element that matches those selectors.

It also lets you package up named behaviors for reuse, and NinjaScript includes a bunch of predefined packaged behaviors for common utilities like AJAX submission and handling graceful degradation cases.

Clone this wiki locally