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:

  '#add_form' : function() {
  '#add_new_link:click' : function() {
    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 %>
	<%= 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' %>
<% 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() {
    $('month').observe('change', function(event) {

Easy peasy lemon squeezy!

~ by moiristo on October 11, 2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: