I'm learning how to use event emitter and inheritance in nodejs. I get the error:
TypeError: this.on is not a function
My code:
const EventEmitter = require('events')
const Emitter = function () {
EventEmitter.call(this)
this.on('event',value => {
console.log('Event emitted',value)
})
}
const myEmitter = new Emitter()
What I'm doing wrong?
With above code you're not actually inheriting from EventEmitter
. I'd just use an actual class that extends
it:
const EventEmitter = require('events')
class Emitter extends EventEmitter {
constructor() {
super();
this.on('event', value => {
console.log('Event emitted', value)
});
}
}
const myEmitter = new Emitter();
myEmitter.emit('event', 'hello'); // logs 'Event emitted hello' to the console.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.