Topic: HOWTO: Implement a site-wide AJAX throbber by rewriting helpers
There's quite a few pieces of code going about that allow you to have a throbber with minimal difficulty (something to indicate to the user the system is working). None of them, however, fulfilled my needs. Grace (my AJAX webmail client) allows widgets (a partial that gets rendered to a specific div) to be dynamically added, and the user should be able to use standard Rails code to integrate them with system, which means that the throbber should work any time any link is clicked. This meant that, for my purposes, I had to rewrite the definition of link_to_remote.
My new definition of link_to_remote is as follows (add it to app/helpers/application_helper.rb):
def link_to_remote(name, options = {}, html_options = {})
options[:before] = "throb();" + options[:before].to_s
options[:complete] = options[:complete].to_s + "; unthrob()"
link_to_function(name, remote_function(options), html_options)
endThis appends a javascript method throb() to the beginning of the generated onClick, and the method unthrob() to the end of it. We'd better write those methods then! Add the following to public/javascripts/application.js:
//Start the throbber
function throb(){
document.getElementById("throbber").innerHTML = "Loading . . .";
}//Stop the throbber
function unthrob(){
document.getElementById("throbber").innerHTML = "";
}
Obviously you want to replace the values innerHTML is set to to whatever you want your throbber to be (animated gifs being the obvious choice), but some text is good enough to demonstrate the principle. Finally, add a div with the id "throbber" to your main layout (somewhere that won't get reloaded by AJAX calls), and Bob's your uncle! All AJAX calls made with link_to_remote will cause the throbber to be displayed while they are working. You can also extend this to other helpers as well (form_remote_tag, submit_to_remote and so on) for site-wide, DRY throbber goodness.
Last edited by Douglas (2007-01-22 21:19:07)