Skip to content

Instantly share code, notes, and snippets.

@LeoAref
Last active October 5, 2022 11:04
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save LeoAref/b6a14d96423a0b558b7de7635fb8f86e to your computer and use it in GitHub Desktop.
Save LeoAref/b6a14d96423a0b558b7de7635fb8f86e to your computer and use it in GitHub Desktop.
Simple event dispatcher implementation using JavaScript
export class Dispatcher {
constructor () {
this.events = {};
}
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;
}
// Check if this event not exists
if (this.events[event] === undefined) {
this.events[event] = {
listeners: []
}
}
this.events[event].listeners.push(callback);
}
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();
});
}
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);
});
}
}
// Example:
const dispatcher = new Dispatcher();
dispatcher.addListener('getUserInfo', (details) => {
console.log(details);
});
dispatcher.dispatch('getUserInfo', {
username: 'John',
accountType: 'admin'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment