Cross-Browser Observer Pattern Implemented In jQuery and Erlang

This post is about my experience implementing a comet server in Mochiweb, which is an Erlang framework for http server development. The goal of this server is to implement an observer pattern, which enables rudimentary transmission of data between browsers. Two jQuery functions, $.talk() and $.listen(), allow web pages to set the json value of a key/value pair, or to be notified when the json value of the key changes.

Before I talk about the implementation, open these two links in separate browser pages to see a simple example of how it's used.

talk and listen

If you look at the source HTML/javascript for those two pages you'll get the idea of how the functions are used.

A page that wants to set a key on the server uses the $.talk() call:

$(document).ready(function() {
  $("#data").keyup(function () {
    $.talk({
      url : "http://conceptfour.com/observer",
      key : "key1",
      token : "19214E0E4EC3B6B09CE6A1CEF6350468",
      data : $("#data").val()
    });
  });
});

http://conceptfour.com/observer is where the Erlang server is listening. The token is for security, so that not just anybody can set a key. It's basically a hash of the IP address of the requesting page, the key, and a secret value. When a page is served, it is given a token, which it can then use in $.talk() to set a specific key. This code basically says "When the textbox gets a keyup event, set the value of key1 to the value of the textbox's contents, and here are my credentials"

A page that wants to get the value of a key, and be notified of any changes to the key uses the $.listen() function:

$(document).ready(function() {
  $.listen({
    url : "http://conceptfour.com/observer",
    key : "key1",
    callback : function(data) {
      $("#result").text(data);
    }
  });
});

Here we provide a callback, so that when the value of key1 is updated, our callback function is called, and we fill a <div/> with the value handed to us.

http://conceptfour.com/observer is actually being forwarded (reverse-proxy) to an HTTP server written in Erlang, using the Mochiweb framework. Long polling is used so that requests for new data only have to be sent occasionally, and the server will immediately relay new data when it gets it.

Now that you've got a taste of what this can do, next we'll take a look at look at $.talk() and $.listen(), and then how the Mochiweb server is implemented.