1. 程式人生 > >Simple usage of events in Node.js

Simple usage of events in Node.js

const events=require("events")
const eventEmitter=new events.EventEmitter()
eventEmitter.on("eat",() => {
    console.log("eat")
    eventEmitter.emit("drink","beer")
})
eventEmitter.on("drink",data => {
    console.log(`drink ${data}`)
    eventEmitter.emit("think")
})
const thinkHandler=() => {
    console.log("think")
}
eventEmitter.addListener("think",thinkHandler)
//eventEmitter.removeListener("think",thinkHandler)
console.log(eventEmitter.listenerCount("eat"))
eventEmitter.emit("eat")