A publish-subscriber module in plain JavaScript

This is a module for implementing the publisher-subscriber pattern (a.k.a Pub-Sub) in JavaScript. If you're not familiar with the benefits of Pub-Sub, take a look at this Stack Overflow post.

The PubSub module below is written in plain JS. It has no dependencies. One special feature is retroactive publishing. If an event is published before a subscriber is added, the subscriber will be called retroactively.

For example, let's say your application includes a list of comments and a comment form. The form broadcasts a commentAdded event when new text is added:

PubSub.publish('commentAdded', commentText);  

The list of comments subscribes to commentAdded:

PubSub.subscribe('commentAdded', function(commentText) {  
// Render the comment

This would cause a race condition with traditional PubSub modules. Because the comments list subscribes to the commentAdded event after the comments form publishes it, the comment will not be rendered. You have to ensure that all the necessary subscribers are listening first.

With the implementation of PubSub below, the subscriber will be notified regardless of when the event was added.