It is already established that any NodeJS class can extend EventEmitter:
const EventEmitter = require('events');
class MyEventEngine extends EventEmitter {
constructor() {
super();
}
crankItUp() {
this.emit('crank', 'Boom Boom Bass!');
}
const boombox = new MyEventEngine();
boombox.on('crank', () => { console.log('Turn that isht up!'); });
boombox.crankItUp(); // 'Turn that isht up!'
But how do I use the event internally within the class itself?
const EventEmitter = require('events');
class MyEventEngine extends EventEmitter {
constructor() {
super();
this.on('crank', () => { console.log('Turn that isht down!'); });
}
crankItUp() {
this.emit('crank', 'Boom Boom Bass!');
}
const boombox = new MyEventEngine();
boombox.crankItUp(); // 'Turn that isht down!'
Is the latter an acceptable pattern?
via toszter
No comments:
Post a Comment