Last active
October 5, 2022 11:04
-
-
Save LeoAref/b6a14d96423a0b558b7de7635fb8f86e to your computer and use it in GitHub Desktop.
Simple event dispatcher implementation using JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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