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 inwatch_results</span> %> <li> <<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(watchresult) }
%>
</li>
<% end %>
</ul>
</div>
The Javascript
application.jsLoadWatchResult = 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