How to build your custom event listener

Event listeners are not that complicated to understand. In fact, you can build your own. And here’s how.

First we want to be able to instantiate multiple event listeners and to do so we can write a small function to be used as constructor.

var EventListener = function() {
 this.events = []; // Empty list of events/actions
}

Javascript does not have classes. However, we can use a function constructor to return a new object that we can then use to create new instances with pre-defined properties and methods. We can use this pattern to emulate classes. And regarding methods... they're simply functions.

A Method is a property of an object that contains a function.

So, next we add methods to the prototype of our function constructor. We do that in order to not duplicate methods on each instance. Methods will be recalled from the prototype, and the listeners will have only the list of events and actions registered for them. That will save us some memory.

We need two methods, one for registering the events to listen for, and another for executing them when time will come.

EventListener.prototype.on = function(event, fn) {
  this.events[event] = this.events[event] || [];
  this.events[event].push(fn);
}

EventListener.prototype.fire = function(event) {
  if (this.events[event]) {
    this.events[event].forEach(function(fn) {
      fn();
    })
  }
}

On the line 2 we verify that a list of actions for a specific event already exists. If not, we create an empty array on the fly. On line 3 we push a callback into that array.

Callbacks are functions that will be executed at some point during run time, in response to an event.

Each event will be registered within the events array, and it will represent the key for its relative sub array. This second level array will contain the callbacks.

The method to execute it is even simpler. First it verifies that a fired event has been previously registered (line 7) and if so it will take the relative sub array, and execute all the listed callbacks in sequence.

Examples

At this point our custom event listener is ready to be used. We can create multiple instances if necessary, but in here I’ll demonstrate how to use one single instance of it for sake of simplicity.

// Initializes the event listener
var EvListener = new EventListener();

// Adding events and callbacks
EvListener.on(‘make-coffee’, function() {
  console.log(‘Here\’is your coffee, Sir.’);
});

EvListener.on(‘make-coffee’, function() {
  console.log(‘Thanks you darling.’);
});

EvListener.on(‘no-more-coffee’, function() {
  console.log(‘We need more coffee…’);
});

// Firing events
EvListener.fire(‘make-coffee’);
EvListener.fire(‘no-more-coffee’);

NodeJS and vanilla JS

I was playing with this code while learning NodeJS. But it works also within more browser-side Javascript applications.

Its purpose is mainly didactic, since Javascript has already event listeners built in. Nonetheless, when we understand how things works, we can generally make a better use of them.