RailsConf 2008: LowPro
Although my colleagues agreed RailsConf 2008 was ‘less interesting than the last time’, there were some interesting presentations I’d like to give some extra attention.
First and foremost, I was very excited about a presentation of LowPro, an extension to prototype to easily ajaxify your webapp with unobtrusive javascript. Forget about link_to_remote, submit_to_remote and remote_form_for, which yield blocks of ugly inline javascript. Instead, consider this script to send a form using AJAX:
Event.addBehavior({
'#add_form' : function() {
this.hide();
},
'#add_new_link:click' : function() {
$('add_form').toggle();
return false;
},
'#add_form' : Remote.Form
});
Using Event.addBehavior, you can add behaviors to elements specified by CSS selectors. When this piece of code is included in your static, non-javascript webapp, it will ‘hijack’ click and submit events only when javascript is enabled.
I have done something similar in a project of my own, which should update a page when a month was selected in a combobox. Note that this example does not use LowPro itself. If javascript was disabled, a button should be displayed to manually submit the form containing the combobox. So, my static page (statistics.html.erb) would look like this:
<% form_tag example_url, :method => :get, :id => 'months-form', :class => 'months-form' do %>
<div>
<%= select_tag :month, @available_months.collect{ |month| "<option value=\"#{month.to_s}\" #{(@curr_moneht.same_month?(month)) ? 'selected="selected"' : '' }>#{month.strftime("%B %Y")}</option>" }.join %>
<%= submit_tag 'view', :id => 'submit-button' %>
</div>
<% end %>
To add a dash of Javascript to this without touching this perfectly fine code, I just need to include a javascript file that should handle the form submission. Let’s call it statistics.js:
<% content_for :content_for_js do %> <%= javascript_include_tag 'statistics' %> <% end %>
And finally, the javascript that should prevent manual form submission and hide the view button when javascript is available:
Event.observe(window, 'load', observeMonthField);
function observeMonthField() {
$('submit-button').hide();
$('month').observe('change', function(event) {
$('months-form').submit();
});
}
Easy peasy lemon squeezy!

Leave a Reply