Well, I found today I needed an Ajax.Responders for something not as trivial as showing an indicator.

On the form, I have event handlers responsible for doing a PUT on each change to the field. This way, the user doesn’t need to remember to save his record when navigating away.

Since I’m working on the contact page, we need to add addresses and phones. I had it all working, except that the new address or phone’s fields weren’t AJAX-enabled.

After reading a bit, I found/remembered about Ajax.Responders. Here’s what it looks like:

 1 XlSuite.FormHandler = Class.create();
 2 XlSuite.FormHandler.prototype = {
 3   initialize: function(root) {
 4     this.root = root;
 5     this.registeredFields = new Hash();
 7     // Register an event handler to be called
 8     // after each Ajax call completes
 9     Ajax.Responders.register({
10       onComplete:
11         this.registerEventHandlers.bindAsEventListener(this)
12     });
13   },
15   registerEventHandlers: function() {
16     var editors = Selector.findChildElements($(this.root), ["input.subtleField", "select.subtleField", "textarea.subtleField"]);
18     for (var i = 0; i < editors.length; i++) {
19       var field = editors[i];
20       if (this.registeredFields[field.id] != field && field.id.substring(0, 4) != "new_") {
21         Event.observe(field, "focus", this.onFocus.bindAsEventListener(this));
22         Event.observe(field, "keypress", this.onKeypress.bindAsEventListener(this));
23         Event.observe(field, "blur", this.onBlur.bindAsEventListener(this));
25         // Remember that we processed this field
26         this.registeredFields[field.id] = field;
27       }
28     }
29   }
31   // rest of implementation omitted
32 );

In initialize, we prepare ourselves a Hash to remember which fields were processed, and not add multiple event handlers for the same field.

Then, in registerEventHandler (which is called on the complete event of the AJAX call), we find which fields to register event handlers on, and flag them as processed.

I didn’t find many example usages of Ajax.Responders. I hope this helps someone.


Your Host

A picture of me

I am François Beausoleil, a Ruby on Rails and Scala developer. During the day, I work on Seevibes, a platform to measure social interactions related to TV shows. At night, I am interested many things. Read my biography.

Top Tags

Books I read and recommend


Projects I work on

Projects I worked on