PubSub event system

Usage no npm install needed!

<script type="module">
  import easyPubsub from 'https://cdn.skypack.dev/easy-pubsub';


Object Publish/Subscribe System

System for object-to-object event publish/subscribing.



Publish an event by calling the publish method and passing the event to publish as the first argument.

Internally, only callbacks register with subscribe will be called, and only ones that match the event name they were registered with.

// Publish event

You can pass any number of additional arguments in the publish method and they will be passed to the callbacks.

// Publish event with any number of arguments
this.publish('eventName', argument1, argument2);


To subscribe to an event callback that will be called in the future (via publish), use the subscribe method.

this.subscribe('eventName', callbackFunction);

When 'eventName' is published in the future, callbackFunction will be called.


To remove a callback previously subscribed, use the unsubscribe method.

// Unsubscribe registered callbackFunction
this.unsubscribe('eventName', callbackFunction);

To remove all callbacks from an event, exclude the callbackFunction parameter.

// Unsubscribe all callbacks in eventName

And finally, to unsubscribe all events and all their respective callbacks, call unsubscribe with no arguments:

// Unsubscribe all events and callbacks on object


The first argument of any callback will always be the event name. Any additional arguments called with the publish method will be included when callbacks are called.

all Event

There is a special all event that you can subscribe to. This event is published when any event is publish on the object. The first argument passed to the callback will still be the event published (not all).

staticObject.subscribe('all', function(event) {
    console.log('this event was published: ' + event)


// Result:
// this event was publish: resize


If you want to capture all events from an object and transfer them to another (bubbling/capture), you can use the capture method:


// subscribe event to parentObject
parentObject.subscribe('eventName', callbackFunction);

// publish event from childObject, which will bubble up to parentObject

Setup an Object for PubSub

To implement PubSub onto an object, there are two methods to doing so:


The PubSub class has an apply method that will attach the publish, subscribe, and unsubscribe methods to the object to pass into it.

var obj = {};



PubSub.apply will return the object that it modified.


The other method of implementing PubSub is to inherit from it using standard JavaScrip prototype inheritance.

var newClass = function() {


newClass.prototype = new PubSub();
newClass.constructor = newClass;

newClass.prototype.onClick = function() {

Supported Browsers

  • Chrome
  • Firefox
  • Safari
  • IE6+