var events = require('events')
var eventEmitter = new events.EventEmitter();
var fn1 = function() {
console.log("first fn executed on triggering first event ")
eventEmitter.emit('fn1')
}
eventEmitter.on("event1", fn1)
eventEmitter.emit('event1')
eventEmitter.on('fn1', function() {
console.log("This is the fn triggered on 2nd event")
})
output on executing it by node event1.js is " first fn executed on triggering first event "
CodePudding user response:
Because the handler is registered after the event is fired. Try this:
var events = require('events')
var eventEmitter = new events.EventEmitter();
var fn1 = function() {
console.log("first fn executed on triggering first event ")
eventEmitter.emit('fn1')
}
eventEmitter.on("event1", fn1)
eventEmitter.on('fn1', function() {
console.log("This is the fn triggered on 2nd event")
})
eventEmitter.emit('event1')