Ajax.Responders

Ajax.Responders.register(responder)
Ajax.Responders.unregister(responder)

A repository of global listeners notified about every step of Prototype-based AJAX requests.

Sometimes, you need to provide generic behaviors over all AJAX operations happening in the page (through Ajax.Request, Ajax.Updater or Ajax.PeriodicalUpdater).

For instance, you might want to automatically show an indicator when an AJAX request is ongoing, and hide it when none are. You may well want to factor out exception handling as well, logging those somewhere on the page in a custom fashion. The possibilities are plenty.

To achieve this, Prototype provides Ajax.Responders, which lets you register (and if you wish to, unregister later) responders, which are objects with properly-named methods. These names are the regular callback names, and your responders can implement any set of interest.

For instance, Prototype automatically registers a responder that maintains a nifty variable: Ajax.activeRequestCount. This contains, at any time, the amount of currently active AJAX requests (those created by Prototype, anyway), by monitoring their onCreate and onComplete events. The code for this is fairly simple:


Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

All callbacks in the life-cycle are available; actually, onCreate is only available to responders, as it wouldn’t make a lot of sense to individual requests: you do know when your code creates them, don’t you? It is triggered even before the XHR connection is opened, which makes it happen right before onUninitialized.

Unregister: remember the reference…

As always, unregistering something requires you to use the very same object you used at registration. So if you plan on unregistering a responder, be sure to define it first, then pass the reference to register, and finally, when the time comes, to unregister.