Live with grace. Write superb software.

I've seen a lot of APIs that have the bad habbit of having the event types described as String. jQuery (JavaScript) and SWT (Java) are two popular examples that allow extensions of the event system using String names. Generally the API is composed by 2 methods:

  1. the Add Listener method: on / addPropertyChangeListener
  2. the Fire Event method: fire / notifyPropertyChange

While the naming conventions are different, in spirit they do the same thing. The problem with this approach that if you do instead of:

element.on("click", function() { ... });


element.on("clickl", function() { ... }); // invalid event type

you won't even notice it unless many hours of pointless debugging have passed.

So I believe that JavaScript APIs (in particular) should go in a different direction, where you could see the problem the moment you try to listen to an event that does not exist, by throwing an exception on the Add Listener method. Thus, another method would be needed to actually register the event type to the specific element, so we will have:

  1. the Register Event method: event / addEvent (?)
  2. the Add Listener method: on / addPropertyChangeListener. Note that this will now throw an exception if an invalid listener will be registered.
  3. the Fire Event method: fire / notifyPropertyChange. This now can also throw an exception if the event was not registered.

Since we're developers here, some API calls would look like:

var element = $("#whatever");
// wrong
element.on("customevent", function() {...}); // throws exception
// good
element.event("customevent"); //now only we can register listeners to it.
// later ...
element.on("customevent", function() {...}); // works just fine.

Note, that it doesn't mean this should be the final API. Personally I think the best looking API is something along the way that after the registration, you could call the API only via members of the on object. Something like this:

element.on.customevent.addListener(function() {...});
element.on.customevent.notify(eventData); // trigger the actual event

But I am convinced that the actual event types should be tied to the object that can generate them.


In my opinion this approach has these advantages:

  • Faster time from the error introduced in the code, to the error report. (we won't generate non existing events, nor listen to non existing ones).
  • The possibility of interrogating an object on what events it can raise at runtime.

The only drawback I can think of, is that you can't listen to events before they are registered, but I haven't yet seen any real life application where this actually happens.


The one to rule them all. The browsers that is.


SharpKnight is an Android chess game.


MagicGroup is an eclipse plugin.