Thursday, August 10th, 2006
Unobtrusive Javascript and Ajax for Rails
<p>Luke Redpath and Dan Web have released Unobtrusive Javascript for Rails. If you've spent time with the Rails javascript helpers, you know that they can be a huge time saver, but tend to produce some nasty code like this:-
-
<form onsubmit="new Ajax.Request('/subscribe/add_ticker', {asynchronous:true, evalScripts:true, onLoading:function(request){ticker_loading()}, parameters:Form.serialize(this)}); return false;" method="post" action="/subscribe/add_ticker">
-
....
-
</form>
-
So you have all of your behavior mixed in with your content, with inline javascript everywhere. Thats bad for business! Dan has written more extensively on how "Rails is the devil on your (client-side) shoulder".
The Unobtrusive Javascript plugin changes that. It allows you to write:
-
<% apply_behaviour "#mylink:click" do |page, element|
-
page.alert "You clicked me! Now watch me fade..."
-
element.visual_effect :fade
-
end %>
To attach fades to links in a page. Or use it with the builtin rails tag helpers:
-
<%= content_tag "div", "My funky box", :onclick => "alert('Hello World!')" %>
The resulting code is attached on load, using prototype events and all that stuff. Very nice! The plugin uses event:Selectors for attaching events dynamically and placing them into an external javascript file. Luke has written a recent note about a fix needed if you are using edge Rails, and also recommends use svn:externals to keep the plugin up to date. The project home page is here, as of right now it just contains the rdocs. I may just have to check this out for my rails work...
Related Content:











Thanks for the heads up Rob.
Just one small note, the latest version of unobtrusive js is using Dan’s own lowpro js library which includes improved event handling code as well as a modified version of event:Selectors – I don’t know the ins and outs of Dan’s JS wizardry but the code is there for everybody to see. Feel free to grab lowpro.js for use elsewhere as well, I know Dan is planning on releasing this separately soon.
Oh, and I should mention the plugin has its own website, currently just the rdocs:
http://opensource.agileevolved.com/unobtrusivejs/
Thanks Luke, I updated the post to have that link, too.
Grab 0.2.3 whilst its hot:
http://www.lukeredpath.co.uk/index.php/2006/08/10/unobtrusive-js-022-the-two-in-one-day-release/
Interesting, Ajax for Python -> Dango?