Unobtrusive javascript/Ajax in Rails

Hello list,

I have been reading a lot about web standards lately, and specially about unobtrusive javascript.

It essentially tells you to get rid of javascript in the view layer ((X)HTML), including event assignment.

Considering all of the default prototype Rails helpers don’t cope with these rules, what would be the best way to implement unobstrusive javascript in a Rails application ? Overriding these helper methods ?

I have found the ujs4rails plugin, but it doesn’t seem to be usable as of now, with Rails 2.x. The last update was back on 2006. Too bad as it seems to be a really cool project.

Any hints greatly appreciated!

Thanks,

Marcelo.

Marcelo de Moraes Serpa wrote:

It essentially tells you to get rid of javascript in the view layer ((X)HTML), including event assignment.

That is UJS's marketing pitch. While there's a lot of benefit in letting a Ruby generator build your Javascript for you, there's still no benefit in hiding absolutely all of it. If your View needs a custom onload='foo()', just go ahead and write a little JS.

Any hints greatly appreciated!

Also, make sure your unit tests cover your JS.

(Unit tests - not "acceptance tests". They should not raise a browser just to spot-check things...)

I normally hook the loaded event in my javascript. So, for example (Prototype):

document.observe('dom:loaded', function() {
   // set up event watchers, etc.
}

or for jQuery:

jQuery.document(ready){function() {
   // set up event watchers, etc.
}

This does not address Philip's concerns with respect to having JavaScript wrapped into unit tests, but it is a viable way to hook things up in an unobtrusive way.

Hope this helps.

s.ross wrote:

document.observe('dom:loaded', function() {
   // set up event watchers, etc.
}

Yet note that's still raw JS - not hidden inside a Ruby layer.

This does not address Philip's concerns with respect to having JavaScript wrapped into unit tests, but it is a viable way to hook things up in an unobtrusive way.

It would work fine. Suppose you need this:

  document.observe('dom:loaded', function() {
     think_about_record(<%= my_record.id %>);
  }

Now you could test with:

  assert_match @response.body, /think_about_record..42/

That would spot-check the business logic went into the view at the right spot. That's quite enough coverage to defend this feature from refactors and upgrades.

Thank you guys for the helpful insights! I appreciate your help.

Marcelo.

I highly reccomend LowPro. LowPro is unobtrusive javascript at its best.

http://www.danwebb.net/2006/9/3/low-pro-unobtrusive-scripting-for-prototype

The problem is that these UJS efforts for Rails all seem to have stopped in time (2006, to be specific). People have lost interest? Why?

The one thing that bugs me is the effort I would need to implement ujs in Rails currently.

Well, let’s see how it goes… I may also not worry about ujs too much right now too.

Thanks!

Marcelo.