Skip to content

Instantly share code, notes, and snippets.

@Mirodil
Last active January 18, 2022 18:51
Show Gist options
  • Save Mirodil/aa016918f6b291046b5b25022e65c6af to your computer and use it in GitHub Desktop.
Save Mirodil/aa016918f6b291046b5b25022e65c6af to your computer and use it in GitHub Desktop.
// Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture
// in which certain kinds of objects (called "emitters") emit named events that cause
// Function objects ("listeners") to be called.
Class: EventEmitter
// Synchronously calls each of the listeners registered for the event named eventName,
// in the order they were registered, passing the supplied arguments to each.
emit(eventName[, ...args])
// Removes the specified listener from the listener array for the event named eventName.
off(eventName, listener)
// Adds the listener function to the end of the listeners array for the event named eventName.
// No checks are made to see if the listener has already been added.
// Multiple calls passing the same combination of eventName and listener will result in the listener being added,
// and called, multiple times.
on(eventName, listener)
// Adds a one-time listener function for the event named eventName.
// The next time eventName is triggered, this listener is removed and then invoked.
once(eventName, listener)
Example:
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
let superbowl = new EventEmitter()
const cheer = function (eventData) {
console.log('RAAAAAHHHH!!!! Go ' + eventData.scoringTeam)
}
const jeer = function (eventData) {
console.log('BOOOOOO ' + eventData.scoringTeam)
}
const gameIsOne = ()=> {
console.log("game is on");
}
superbowl.on('touchdown', cheer);
superbowl.on('touchdown', jeer);
superbowl.once('game', gameIsOne);
superbowl.emit('game');
superbowl.emit('game');
superbowl.emit('touchdown', { scoringTeam: 'Patriots' });
superbowl.removeListener('touchdown', jeer);
superbowl.emit('touchdown', { scoringTeam: 'Seahawks' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment