Extend Drupal's autocomplete Javascript with your own

Drupal 7's autocomplete Javascript is very functional, but a client wanted to increase the delay after which your browser thinks you've stopped typing, for specific accessibility reasons. They also wanted to make an initial call to the AJAX callback on page load, to potentially "warm a slow cache" on a third-party service, and speed up later AJAX calls.

The Javascript is functional, but not straightforwardly extensible. To extend the particular component that makes the AJAX calls, you need to introduce your own Javascript and implement prototypal inheritance. In practice, this means doing three things:

  1. Replacing the Drupal.ACDB object constructor with a new one, initially empty.
  2. During the replacement's constructor, call the old object's constructor.
  3. Object-create the old object-constructor's prototype, as the new one's prototype, to tie up the inheritance chain.

That sounds pretty complicated, but the following illuminates all three steps in what I hope is a really straightforward way:

/**
 * @file
 * Extend the autocomplete JS for custom behaviour.
 */
 
(function($) {
  // Keep a record of the old ACDB object, but only within this scope.
  var oldACDB = Drupal.ACDB;
 
  // Create a custom replacement.
  Drupal.ACDB = function (uri) {
    // Prototypal inheritance, part 1: call the parent's constructor.
    oldACDB.call(this, uri);
 
    // Implement a longer delay on this replacement object.
    this.delay = 1000;
 
    // Warm up the cache by making a sample AJAX call, right now.
    $.ajax({
      type: 'GET',
      url: this.uri + '/test'
    });
  };
 
  // Prototypal inheritance, part 2: re-use the parent's prototype.
  Drupal.ACDB.prototype = Object.create(oldACDB.prototype);
})(jQuery);

And that's it. You now have control over Drupal's autocomplete-AJAX-calling object. You must strive to use this power for good!