DevLeague Coding Bootcamp
DevLeague is a Full Stack Coding Bootcamp
const EventEmitter = require('events');
Objects that are subclasses of EventEmitter
may have functions attached to them.
These functions are called listeners, or event handlers,
and are invoked when an event is emitted by that object.
Events are named using a string, such as "complete" or "error".
When the event handler is invoked by an event being emitted,
the context of the event handler function
is the object that it is listening on.
emitter.addListener(event, listenerCb);
^---- callback function
v---- event name
emitter.on(event, listenerCb);
Alias
emitter.emit(event);
emitter.removeListener(event, listener)
^---- event handle function
v---- event name
class Timer {
constructor () {
super();
setInterval(() => {
// do something every 1000ms
}, 1000);
}
}
const EventEmitter = require('events');
class Timer extends EventEmitter {
constructor () {
super();
setInterval(() => {
// do something every 1000ms
}, 1000);
}
}
const myTimer = new Timer();
myTimer.addListener('tick', () => {
process.stdout.write('tick \n');
});
class Timer extends EventEmitter {
constructor () {
super();
setInterval(() => {
this.emit('tick');
}, 1000);
}
}
class Timer extends EventEmitter {
constructor () {
super();
this.count = 0;
setInterval(() => {
this.emit('tick', { interval: this.count++ });
}, 1000);
}
}
like callback arguments
myTimer.addListener('tick', event => {
process.stdout.write(`tick ${event.interval}\n`);
});
function tickHandler(event) {
process.stdout.write(`tick ${event.interval}\n`);
}
myTimer.addListener('tick', tickHandler);
function tickHandler(event) {
process.stdout.write(`tick ${event.interval}\n`);
if(event.interval == 5){
myTimer.removeListener('tick', tickHandler);
}
}
myTimer.addListener('tick', tickHandler);
function tickHandler(event){
process.stdout.write(`tick ${event.interval}\n`);
if(event.interval == 5){
this.removeListener('tick', tickHandler);
}
}
myTimer.addListener('tick', tickHandler);
class Timer extends EventEmitter {
constructor () {
super();
this.count = 0;
setInterval(() => {
this.emit('tick', { interval: this.count++ });
}, 1000);
}
}
look for objects or classes that extend EventEmitter
it means you can listen for events that it will emit
check the class api documentation or source code
for what events it will emit, and the contents of the event object it passes back to the handler
emitter.on('data', function(event){...});
What are you ? -----v
^----- What other events do you emit?
By DevLeague Coding Bootcamp