Simple event dispatcher implementation using JavaScript

This is a simple implementation of a dispatcher, to support the same features in the Flux dispatcher.


Create the Dispatcher class:

export class Dispatcher {
constructor () {
this.events = {};
}
}

We create and export the class, then create the constructor function that just creates a property events, to store the dispatcher instance events.

Create the first method “addListener”:

addListener (event, callback) {
// Check if the callback is not a function
if (typeof callback !== 'function') {
console.error(`The listener callback must be a function, the given type is ${typeof callback}`);
return false;
}
    // Check if the event is not a string
if (typeof event !== 'string') {
console.error(`The event name must be a string, the given type is ${typeof event}`);
return false;
}

// Create the event if not exists
if (this.events[event] === undefined) {
this.events[event] = {
listeners: []
}
}

this.events[event].listeners.push(callback);
}

We add a new listener with simple four steps:

  • Check if the given callback is a function.
  • Check if the given event is a string (We can also allow events with numbers).
  • Create the event if not exists.
  • Push the callback to the event listeners list.

Create the “removeListener” method:

removeListener (event, callback) {
// Check if this event not exists
if (this.events[event] === undefined) {
console.error(`This event: ${event} does not exist`);
return false;
}

this.events[event].listeners = this.events[event].listeners.filter(listener => {
return listener.toString() !== callback.toString();
});
}

Now we implement the removeListener method, it allows removing the listener from the listeners list for a certain event.

There are many implementations of the removing step:

  • Return the listener index after adding it in the addListener method, then the user can send it in the removeListener method instead of the callback function.
  • Can get the listener length of that event, and use while(len — ) to go through the list, and check if the given callback equals the list[len] listeners, and if yes >> remove it and break the loop;
  • Use the array filter method (the most simple way) to filter the listeners.

The last method “dispatch”:

dispatch (event, details) {
// Check if this event not exists
if (this.events[event] === undefined) {
console.error(`This event: ${event} does not exist`);
return false;
}
    this.events[event].listeners.forEach((listener) => {
listener(details);
});
}

We will go through that event listeners, and fire the callback with the given details data.


Example of using the dispatcher

import Dispatcher from 'dispatcher';
const dispatcher = new Dispatcher();
// Add a listener to "getUserInfo" event 
dispatcher.addListener('getUserInfo', (details) => {
console.log(details);
});
// Calling the API and dispatch the response data
dispatcher.dispatch('getUserInfo', {
username: 'John',
accountType: 'admin'
});

In this simple example, we imported the dispatcher class, and created an instance.

Then used two methods: addListener to listen to certain event “getUserInfo” and dispatch to dispatch it after getting the response from the API.

Here is the full implementation of the dispatcher https://goo.gl/hhaZfP.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.