This article will take you to understand the EventEmitter in node, and briefly talk about asynchronous operations, error events, and the EventEmitter class. I hope it will be helpful to everyone!
events is the built-in event trigger of nodejs , events are used in many of node's built-in modules. For example, http.server triggers an event every time it receives a request, and stream uses on to listen to corresponding events based on events.
All objects that trigger events are EventEmitter instances. These objects expose EventEmitter.on('event', callback). EventTmitte.on is usually used to register events, and EventEmitter.emit triggers events.
Example:
const events= require('events'); const event=new events();//实例化EventEmitter event.on('data',(a,b)=>{ console.log('参数'+a+b) console.log(this,'this') //注意,如果callback是 箭头函数的话this指向的是全局对象 // 如果callback是function(){}形式的话,this会绑定到EventEmitter实例上 console.log('emit触发了data事件') }) event.emit('data',1,2); //使用emit触发事件
Asynchronous operation
Because EventEmitter.on('event name',callback) The callback in is executed synchronously, but in some cases we have to use asynchronous operations, so we can use SetImmediate to perform asynchronous operations
const events= require('events'); const event=new events(); event.on('event', (a, b) => { setImmediate(() => { console.log('this happens asynchronously'); }); //因为这里的监听器是同步执行的,但是我们可以使用setImediate函数等待监听器里的其他内容执行完再执行 }); event.emit('event',1,2);
trigger once
When we normally trigger events through emit, emit will be triggered several times if there are several events, but we can use once to register events, and events triggered using once can only be triggered once
const EventEmitter =require('events'); const MyEventEmitter=new EventEmitter(); let a=0; //正常注册事件和触发 MyEventEmitter.on('add',()=>{ a++ console.log(a) }) MyEventEmitter.emit('add'); // 1; MyEventEmitter.emit('add'); // 2; // 使用once注册 MyEventEmitter.once('add',()=>{ a++ console.log(a); }) MyEventEmitter.emit('add') // 1 MyEventEmitter.emit('add') // 不生效了
error event
EventEmitter does not have an error event, so when an error occurs, it can only be forced to exit execution, so we must register an error event ourselves. So that the error event is triggered when an error occurs
const EventEmitter=require('events'); const MyEventEmitter=new EventEmitter(); MyEvenEmitter.on('error',(err)=>{ console.error(err,'报错了') })
In addition to the above method, we can also use errorMonitor to monitor the error triggered by emit without registering the error event. Using errorMonitor, we no longer need to manually register error events
const {EventEmitter,errorMonitor}=require('events'); const MyEventEmitter=new EventEmitter(); MyEventEmitter.on(errorMonitor,(err)=>{ console.log(err); }) MyEventEmitter('error' , new Error('报错了'))
EventEmitter class
newListener event
The newListener event will be triggered when we add an event listener, so we can register the newListener event to do something when adding an event listener
const {EventEmitter}=require('events'); const MyEvent=new EventEmitter(); MyEvent.on('newListener',(name,litener)=>{ //name就是正在监听的事件的名称 //listener是事件的处理函数 MyEvent.on('event',()=>{ console.log('在newListener添加的事件') }) }) MyEvent.on('event',()=>{ console.log('正常注册的event事件') }) //此时我们再不触发event事件的情况下,newListener事件就会执行,因为我们只要正在注册事件就会触发newListener事件 //注意:newListener事件必须要使用EventEmitter.once()注册,因为如果我们在newListener事件里再去添加注册事件的话,而且外边有多个注册事件就会触发多次newListener事件,就会发生堆栈溢出 MyEvent.emit('event'); //打印的结果 // 在newListener注册的事件 // 正常注册的event事件
removeListener event
The removeListener event is used to delete registered events. However, removeListener will not prevent events that are being triggered by emit.
const callbackB=()=>{ console.log('B') } const callbackA=()=>{ console.log('A') event.removeListener('data',callbackB) } event.on('data',callbackA) event.on('data',callbackB) event.emit('data'); //在执行callbackA的时候删除了data,但是不会阻止掉下一个emit的触发 event.emit('data'); //在这里的时候才是真正被删除掉了
addListener has the same effect as on
eventNames
Returns an array containing the names of all registered events
const {EventEmitter} =require('events'); const MyEvent=new EventEmitter(); MyEvent.on('data',()=>{}); MyEvent.on('finish',()=>{}); console.log(MyEvent.eventNames()); //打印结果 ['data','finish']
getMaxListeners
Returns the maximum number of events that can be registered. The default is 10. If there are more than 10, there will be a warning. But we can modify it through setMaxListener(20)
const {EventEmitter} =require('events'); const MyEvent=new EventEmitter(); console.log(MyEvent.getMaxListener()); //10 event.setMaxListener(20); console.log(MyEvent.getMaxListener(20));
listenerCount
Return the number of registered events
const {EventEmitter} =require('events'); const MyEvent=new EventEmitter(); MyEvent.on('data',()=>{}); MyEvent.on('data',()=>{}); MyEvent.on('finish',()={}); console.log(MyEvent.listenerCount()) // 2
More node related knowledge, Please visit: nodejs tutorial!
The above is the detailed content of Let's talk in depth about EventEmitter in node.js. For more information, please follow other related articles on the PHP Chinese website!