Callbacks in Unobtrusive Javascript in Rails 3

First, remove all Rails 2 stuff and add the Rails 3 :remote option.

<% form_tag url_for(:action => "run"), :id => "tool-form", :remote => true do %>

Then, bind the function to toggle the spinner visibility to the appropriate AJAX events. Also, on success replace the content of #response with the response data.

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#tool-form")
    .bind("ajax:loading",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(data, status, xhr) {
      $("#response").html(status);
    });
});

This was the only place I found that talked about the Rails 3 javascript callbacks. It’s much better having it in javascript, but that also means that you need something to manage it in the javascript files. I’d recommend something like Sammy.js or backbone.js to have something to hang it on. Otherwise, it gets unwieldy quickly.

 

Advertisements

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