Unobtrusive Javascript with Lowpro and Ruby On Rails

Check out http://www.danwebb.net/lowpro for more info on LowPro, a very elegant approach to do Unobtrusive Javascript with Ruby On Rails. Find hereafter a small example of how to add a custom behavior to link.

The View

watch_results.erb
<%= javascript_include_tag 'prototype', 'lowpro', 'remote', 'application' %> <div id="result_list"> <ul> <% for watch_result in @watch_results %> <li> <%= link_to watch_result.created_at.to_s(:db), diff_watch_result_url(@watch, watch_result), {:id = <%= javascript_include_tag ‘prototype’, ‘lowpro’, ‘remote’, ‘application’ >
<div id
=
"result_list">
<ul>
< for
watch_result in watch_results</span> %&gt; &lt;li&gt; &lt;<span class="s"><span class="dl">%=</span><span class="k"> link_to watch_result.created_at.to_s(:db), diff_watch_result_url(watch, watch_result),
{:id
=
> dom_id(watch
result) }
%>
</li
>

<% end %>
</ul>
<
/
div>

The Javascript

application.js
LoadWatchResult = Remote.Link({ onLoading : function() { $('watch_result_difference').innerHTML=''; $('watch_result_difference').addClassName('pleaseWait'); }, onComplete : function(e) { var source = Event.element(e); $('watch_result_difference').removeClassName('pleaseWait'); $$('div#result_list ul a.active').each(function (e) {e.removeClassName('active')}); source.addClassName('active'
LoadWatchResult = Remote.Link({
onLoading : function() {
$(watch_result_difference).innerHTML=;
$(watch_result_difference).addClassName(pleaseWait);
},
onComplete : function(e) {
var source = Event.element(e);
$(watch_result_difference).removeClassName(pleaseWait);
$$(div#result_list ul a.active).each(function (e) {e.removeClassName(active)});
source.addClassName(active);
}
});

Event.addBehavior({
#result_list ul li a: LoadWatchResult
});

The ‘remote.js’ provides additional behaviors creatde by Dan Wedb as part of LowPro (http://svn.danwebb.net/external/lowpro/trunk/behaviours/). The LoadWatchResult behavior we created in this example transforms a ‘standard’ link_to to a link_to_remote with additional behavior on the onLoading and onComplete of the remote call. The view stays clean.

Enjoy!
Daniel

Posted by Daniel Wanja Tue, 28 Aug 2007 02:41:41 GMT