|
| 1 | +// import the base? class, EventEmitter from the events module |
| 2 | +const { EventEmitter } = require('events') |
| 3 | + |
| 4 | +// create some listener functions to handle when the events occur. |
| 5 | +// `foo` is expecting two parameters to be passed in. |
| 6 | +const foo = function foo(baz, qux) { |
| 7 | + console.log(`foo executed. baz: ${baz}, qux: ${qux}`) |
| 8 | +} |
| 9 | + |
| 10 | +const bar = function bar() { |
| 11 | + console.log('bar executed.') |
| 12 | +} |
| 13 | + |
| 14 | +const errorProne = function foo(obj) { |
| 15 | + this.emit('error', 'I am just not going to work') |
| 16 | +} |
| 17 | + |
| 18 | +// create an emitter and bind some events to it |
| 19 | +const eventEmitter = new EventEmitter() |
| 20 | + |
| 21 | +// Bind the connection event with the listner1 function |
| 22 | +eventEmitter.addListener('foo', foo) |
| 23 | + |
| 24 | +// N.B. `addListener` is the same as `on`. |
| 25 | + |
| 26 | +// Bind the connection event with the listner2 function - |
| 27 | +// IMPORTANT!! Listeners are called synchronously in the order in which they were added. |
| 28 | +// - i.e. `foo` will be called, and `bar` will be called once `foo` has completed. |
| 29 | +// This is to prevent race conditions and logic errors. |
| 30 | +// They can switch to an async mode using `setImmediate`. |
| 31 | + |
| 32 | +eventEmitter.once('bar', bar) |
| 33 | +eventEmitter.once('liveDangerously', errorProne) |
| 34 | + |
| 35 | +// handle errors in one of the listeners handlers |
| 36 | +eventEmitter.on('error', (err) => { |
| 37 | + console.error('There was an error!') |
| 38 | +}) |
| 39 | + |
| 40 | +for(let i = 0; i < 3; i++ ) { |
| 41 | + eventEmitter.emit('foo', 'value1', 'value2') |
| 42 | + eventEmitter.emit('bar') |
| 43 | + eventEmitter.emit('liveDangerously') |
| 44 | +} |
| 45 | + |
| 46 | +const eventListeners = EventEmitter.listenerCount(eventEmitter, 'foo') |
| 47 | + |
| 48 | +console.log(EventEmitter.listenerCount(eventEmitter, 'connection') + " Listner(s) listening to connection event") |
| 49 | +console.log(eventListeners + " Listner(s) listening to connection event") |
| 50 | +console.log('end of file...') |
0 commit comments