Aug 06

Enjoying the Observer pattern with custom events

Ajax, Tech with tags: , , 26 Comments »

I created an introductory example discussing custom events as an implementation of the Observer pattern.

The example dynamically adds functionality based on checkboxes to simulate events that could change processing and uses the fire() and observe() methods from Prototype.

I strap on behaviour to a list of names. When you click on the name, something can happen. To do this I could have done the following:

$$('ul#leftchoices li').each(function(el) {
    el.observe('click', function(e) {
        if ($('colorchange').checked) {

        if ($('contentchange').checked) {

In the click event itself, I do various checks and kick off behaviour. That can be fine for small actions, but what if you want to do more? This is when I prefer to abstract out the action and just fire an event:

$$('ul#leftchoices li').each(function(el) {
    el.observe('click', function(e) {'selected:choice');

At this point, this bit of code becomes dumb. It doesn’t know what to do when you select the item, and it just hopes that somewhere, someone is listening. That is where the observers come in, such as this one that changes the main content based on the selected name:

$('contentchange').onchange = function(e) {
    if ( {
        document.observe('selected:choice', changeContent);
    } else {
        document.stopObserving('selected:choice', changeContent);

When someone clicks on the checkbox, this method is fired and an observer is either added, or taken away.

Once you start building applications with this in mind, you may find a bit of a sea change. You start to think about the various events as a public API that you can easily expose to observers. Gone is the simple ability to look at one method and see what is happening, but the loose coupling gives you the ability to easily layer in your architecture. Based on some settings, behaviour can be dynamically added. You could even expose these events in a way that makes it easier for Greasemonkey hackers to come in and work with your application. All in all, a win-win for anything more than a simple example.

Although this example uses Prototype, you could do the same with the other top class JavaScript libraries. In fact, if someone wants to port this example to Dojo, jQuery, Mootools, YUI, or anything else, send me the files and I will put them up so we can all compare how custom events are done in the various toolkits.

UPDATE: We now have Prototype, jQuery, DOMAssistant, and Appcelerator versions. Thanks Malte!

Dec 27

Gears Future APIs: Messaging API

Ajax, Gears, Google, Tech with tags: , , 2 Comments »

Once you start delving into the WorkerPool API, you quickly see how a common pattern would be using it as a messaging system. As it stands, it looks like an Open Web version of Erlang processes.

Scott Hess wrote up his thoughts on a more formal Messaging API based on WorkerPool:

Gears WorkerPool has two pieces, the part about running a bit of JS asynchronously, and the part about trading messages with that JS. This API may be composable from more basic bits. The messaging bit could be used in other contexts, such as implementing something like WhatWG’s postMessage().

Aside: What is WhatWG’s postMessage?

postMessage is “a messaging system that allows documents to communicate with each other regardless of their source domain, in a way designed to not enable cross-site scripting attacks.”

Here is an example:

For example, if document A contains an object element that contains document B, and
script in document A calls postMessage() on document B, then a
message event will be fired on that element, marked as originating from
document A. The script in document A might look like:

var o = document.getElementsByTagName('object')[0];
o.contentWindow.postMessage('Hello world');

To register an event handler for incoming events, the script would use
addEventListener() (or similar mechanisms). For
example, the script in document B might look like:

document.addEventListener('message', receiver, false);
function receiver(e) {
  if (e.domain == '') {
    if ( == 'Hello world') {
    } else {

This script first checks the domain is the expected domain, and then
looks at the message, which it either displays to the user, or responds
to by sending a message back to the document which sent the message in
the first place.

Back to the Gears Messaging API

Scott gives an example of the messaging API, starting with an end point:

var port = google.gears.factory.create('beta.messageport', '1.0');
port.onmessage = function(port, msg, sender) {
  alert("message: " + msg);
port.listen("name");   // Omit for anonymous listener.

and having a way to send it a message:

var port = google.gears.factory.create('beta.messageport', '1.0');"name");
port.sendMessage("hello there");

To enable cross domain, you can, domain), and on the other side, you have to allow it via something like port.allowCrossOrigin(["", ""]);.

I am excited about a messaging API, as I think that it fits into the way in which we are developing new Web applications. Having an asynchronous queue that allows me to replay work (e.g. offline), and work nicely with Comet based interactions, would be great. We can reuse all that we have learned from other event based systems, and Gregor can rename his book and be happy!

Other Future APIs

Disclaimer: This is early days, and who knows what the final API will look like, or if it will even make it. Do you have ideas for cool Gears that make the Web better? Let us know!.