Listen and respond to ajax_command_replace() I have a page where a block is dynamically reloaded when the user clicks a link. Rather than writing my own js, I'm trying to do this the Drupal way and using Drupal's own ajax_command_replace() like so:

function page_callback($type = 'ajax') {
    if ($type == 'ajax') {
    // Load block
    // ....
    $commands[] = ajax_command_replace('#block-watch-notifications', $output);
    $page = array(
       '#type' =&gt; 'ajax',
       '#commands' =&gt; $commands,
    );
    ajax_deliver($page);
}


And all this works just fine.

The problem is that I need to respond to this event on my page. The js event DOMSubtreeModified would work here if it were reliably implemented by browsers, but it's not. 

However, jQuery's AJAX command also issues its own series of global events, including ajaxComplete. The problem is that, however Drupal is doing its AJAX magic, it isn't raising this event.

How can I listen for ajax_command_replace() having done its work on my page?
From what I can tell, Drupal behaviors are simply callback functions that are called in two cases: 1. when the page is loaded initially, and 2. when content is added/removed via ajax.

You add your callback function to the global js object Drupal.behaviors (US spelling), namespaced by your module's name. My module is called 'watch' so I attach my callback functions to Drupal.behaviors.watch. Drupal.behaviors.MODULE_NAME is itself an object and has two elements that may be named 'attach' and 'detach'.

'Attach' is called during the initial page load and whenever Drupal's ajax adds new content. 'Detach' is called when is Drupal's ajax removes content, either before adding replacement content or removing it forever.

For the record my javascript looked like this:

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      // This code is fired both when the page is 'ready'
      // in the jquery sense, and when new content
      // is 'attached' via Drupal ajax. The settings
      // values that are available to us here
      // are provided in the third parameter of
      // ajax_command_replace() as an associative array.
      // My new content is already part of the dom
      // so I can act on it here.
    },
    detach: function(context, settings, trigger) {
      // Example detach callback.
    }
  }
})(jQuery);


I'm guessing Drupal behaviors can be extended to include all sorts of other behaviors beyond attach and detach and is probably very flexible besides, but that's beyond me right now.