Trapping XMPP events within DOM

Description: This page explains how to make XML documents respond to data and RPC calls sent to the document.

There are three functions that may be declared within the client XML document that may be called by the Gradient client, in effect firing events within the document. These events effectively allow the document to respond to RPC calls and process data sent via presence message stanzas.

processPresence and processMessage

Both functions are called with identical arguments for different stanza types. As their names suggest, if declared these functions will be called when a presence or message stanza is received from the server from which the document was loaded.

If declared, both these functions take as a first argument an array of the child elements of the stanza, and as the second the stanza type. For example:

For messages, the type will be one of "normal", "chat", "groupchat", "headline", or "error".

For presence, the type will be one of "available" "chat", "away", "xa", "dnd", or "invisible".

function processPresence(elements, type) {
  log("presence received, type:"+type);
  for(var e in elements) {
    log(e.tagName);
  }
}

function processMessage(elements, type) {
  log("message received, type:"+type);
  for(var e in elements) {
    log(e.tagName);
  }
}

processIQ

As the name suggests, if declared this function will be called when a GET or SET IQ is received from the server from which the document was loaded.

These functions take as a first argument the child element of the stanza, and as a second either "get" or "set".

In addition, this function MUST return an element. For example:

function processIQ(element, type) {

  if(element.getTagName() == "getNumChildren") {

    var numChildren = document.createTextNode(document.getDocumentElement().getChildNodes().getLength());
    element.appendChild(numChildren);

  } else {

    var whuh = document.createTextNode("Je suis désolé, je ne parle pas Mongol");
    element.appendChild(whuh);

  }
  return element; /* mandatory! */
}

The above example returns the given element as a convenience. Using document.createElement is equally valid.

How these events are called from the server is explained in the server documentation.

© 2006. Some rights reserved. Author: Ian Sollars.