Lightweight Javascript Event Handling Library

July 25th, 2008

A super-lightweight Event Handling javascript library:

// Author: Marcus.Westin@gmail.com, July 25th

function EventBroadcaster(signals) {
  this.events = {};
  for (var i=0; i < signals.length; i++) {
    this.events[signals[i]] = [];
  }
}

EventBroadcaster.prototype.subscribe = function(signal, args){
  if (!this.events[signal]) { throw ('EventBroadcaster.prototype.subscribe: event name not recognized: ' + signal); }
  if (!args.handler) { throw ('EventBroadcaster.prototype.subscribe: no handler given.')}
  args = args || {};
  function makeArray(arg) {
    return arg ? (arg instanceof Array ? arg : [arg]) : [];
  }
  this.events[signal].push({
    handler : function(handlerArgs){
      args.handler.apply((args.scope || window), makeArray(args.curry).concat(makeArray(handlerArgs)));
    },
    once : args.once
  });
}

EventBroadcaster.prototype.once = function(signal, args) {
  args = args || {};
  args.once = true;
  this.subscribe(signal, args);
}

EventBroadcaster.prototype.broadcast = function(signal, broadcastArgs) {
  if (!this.events[signal]) { throw ('EventBroadcaster.prototype.broadcast: event name not recognized: ' + signal); }
  var subscriptions = this.events[signal];
  for (var i=0; i < subscriptions.length; i++) {
    subscriptions[i].handler && subscriptions[i].handler(broadcastArgs);
    subscriptions[i].once && delete subscriptions[i];
  }
}


A Demo is available of a 50-lines mockup Email client interface using the event library for : Event handling is a great pattern for a system with many complex components than need to interact in a loosely coupled manner. For example, in an email UI where the user clicks on an unread email, at least two things have to happen:

  • The central view changes to the content of the email
  • The inbox “unread” count decreases by one

Intuitively, the unread email link could “tell” the central view to change as well as “tell” the inbox count to decrease. However, what if you want to add a third functionality, e.g.

  • notify the server that the email has been read

An alternative intuition says that as the email link has to notify more and more components of what happened, rather than running around to each one of them it could just do a general “Email X was activated!” and each component that cares could then act accordingly. This is how an event management system with Subscribe and Publish (PubSub) works, and allows for among other things a stepwise development process of complex UI’s.

Comments are closed.