Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Mar 13

HowTo: create a unique behavior for Ajax callbacks

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

This is not a strict Ruby on Rails related post but i found it very useful while developing a project with tons of Ajax, if you need to bind the same behavior to a specific callback for all the Ajax requests in your application ( for example show a ‘Loading’ red word while executing an Ajax request ) simply do the following:

  • Download and copy into your script folder the amazing Eventselectors Library from Justin Palmer;
  • Load this library from your layout page;
  • Modify the code at the end of the eventselector.js adding your global behaviors, like;

/* before */

Ajax.Responders.register({
  onComplete: function() {EventSelectors.assign(Rules);}
})

/* after */

Ajax.Responders.register({
  onComplete: function() { Element.hide('loading'); EventSelectors.assign(Rules);},
  onLoading: function() { Element.show('loading'); }
})

/*
    Doing this i just show a 'loading' element on the page each 
    time the user perform a remote action
*/


You can use all the callbacks avaiable from the Prototype.js library and say goodbye to all your link_to_remote :loading options !

Comments

  • Harold Ship

    Posted on March 15

    Nice article. Small error: your title has a typo in it. Should be "behavior".
  • Sandro

    Posted on March 15

    Thank you Harold, fixed :)
  • Acronyms

    Posted on March 16

    Thanks for a tip. I used similar approach, but with changed classes for 'loading element'

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory