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