Skip to content

Instantly share code, notes, and snippets.

@drblue
Created April 6, 2020 15:12
Show Gist options
  • Save drblue/b2a99de856076f60059b26330e474d98 to your computer and use it in GitHub Desktop.
Save drblue/b2a99de856076f60059b26330e474d98 to your computer and use it in GitHub Desktop.
node.js event emitter demo (es6)
/**
* events
*/
const events = require('events');
class Person extends events.EventEmitter{
constructor(name){
super();
this.name = name;
}
}
let derek = new Person('Derek');
let linus = new Person('Linus');
let simone = new Person('Simone');
let tom = new Person('Tom');
let people = [derek, linus, simone, tom];
people.forEach(person => {
person.on('speak', msg => {
console.log(`${person.name} said: ${msg}\n`);
});
});
derek.emit('speak', 'In Quantum Mechanics, if you know the Quantum State of a particle, that is it\'s wave function you can use the Schrodinger equation to calculate what that particle will do in the future.');
linus.emit('speak', 'But it has basically zero competition in this price bracket, so we absolutely needed to take a look at it. Just like I need to tell you about our sponsor - Storyblocks!');
simone.emit('speak', 'My track record isn\'t terribly impressive so far, but I have an angle grinder, and a welder, and I\'m not afraid to use them.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment