Home > Article > Web Front-end > Detailed explanation of Node.js: events event module
Most of the core APIs of Nodejs are designed based on asynchronous event-driven design, and all objects that can distribute events are instances of the EventEmitter class.
As we all know, since nodejs runs in a single thread, nodejs needs to use event polling to continuously query event messages in the event queue, and then execute the callback function corresponding to the event, which is somewhat similar to the message mapping mechanism of windows. As for the more detailed implementation links, you can find information separately.
The following introduces the use of EventEmitter.
1. Listening for events and distributing events
EventEmitter instances can use on or addListener to listen for events and the emit() method to distribute events, as shown below:
const events = require('events'), EventEmitter = events.EventEmitter, util = require('util'); function myEmiter(){ EventEmitter.call(this); }; util.inherits(myEmiter,EventEmitter);//继承EventEmitter类 const myEmitterIns = new myEmiter(); myEmitterIns.on('data',(o)=>{ console.log('receive the data:'+o.a); });
or use the class class
class myEmiter extends EventEmitter{}//继承EventEmitter类 const myEmitterIns = new myEmiter(); myEmitterIns.on('data',(o)=>{ console.log('receive the data:'+o.a); }); myEmitterIns.emit('data',{a:1});
The execution results are as follows:
E:developmentdocumentnodejsdemo>node event-example.js
receive the data:1
2. Pass parameters to the event listening callback function
As can be seen from the above example, the emit() method can Pass any set of parameters to the callback function. One thing to note is that the this keyword points to the EventEmiter instance that calls the emit method, except in the arrow function. This points to the global this, because this in the arrow function is defined time binding. As shown below:
class myEmiter extends EventEmitter{} const myEmitterIns = new myEmiter(); myEmitterIns.on('data',function(data){ console.log("普通回调函数中this:"); console.log(this); }); myEmitterIns.on('data1',(data1)=>{ console.log("箭头回调函数中this:"); console.log(this); }); myEmitterIns.emit('data',{a:1}); myEmitterIns.emit('data1',{a:1});
The execution result is as follows:
E:developmentdocumentnodejsdemo>node event-example.js
This in the ordinary callback function:
myEmiter {
domain: null,
_events: { data: [Function ], data1: [Function] },
_eventsCount: 2,
_maxListeners: undefined }
this in the arrow callback function:
{}
Here we talk about this in the arrow function. By the way, why the arrow function can be implemented Binding this when defining is because there is no mechanism to bind this inside the arrow function. It uses this in the outer scope, so it cannot be used as a constructor.
3. Execution sequence of event listener
EventEmiter instance can bind multiple events. When we trigger these events sequentially, EventEmiter will execute in synchronous mode. Even if the first event processing function is not completed, it will not Trigger the next event as follows:
class myEmiter extends EventEmitter{} const myEmitterIns = new myEmiter(); myEmitterIns.on('data',function(data){ console.time('data事件执行了'); for(var i = 0 ; i< 100000; i++) for(var j = 0 ; j< 100000; j++) ; console.timeEnd('data事件执行了'); }); myEmitterIns.on('data1',(data1)=>{ console.log("data1事件开始执行..."); }); myEmitterIns.emit('data',{a:1}); myEmitterIns.emit('data1',{a:1});
The execution result is as follows:
E:developmentdocumentnodejsdemo>node event-example.js
data event executed: 4721.401ms
data1 event started execution...
Of course, we can use asynchronous operations in the callback function, such as setTimeout, setImmediate or process.nextTick(), etc., to achieve asynchronous effects, as shown below:
myEmitterIns.on('data',function(data){ setImmediate(()=>{ console.log('data事件执行了...'); }); });
The execution results are as follows:
E:developmentdocumentnodejsdemo> node event-example.js
data1 event was executed...
data event was executed...
4. One-time event monitoring
EventEmiter can use once to listen to an event, then the event handler will only trigger Once, the event will be ignored after emit because the listener is logged out, as shown below:
myEmitterIns.once('one',(data)=>{ console.log(data); }); myEmitterIns.emit('one','this is first call!'); myEmitterIns.emit('one','this is second call!');
The execution results are as follows:
E:developmentdocumentnodejsdemo>node event-example.js
this is first call!
From the above results, it can be seen that the 'one' event is only executed once.
5. Remove event binding
Similar to DOM event listening, EventEmiter can also remove event binding. Use the removeListener(eventName, listener) method to unbind an event, so the callback function listener must be a named function. , otherwise the function cannot be found, because the function is a reference type, even if the function body is the same, it is not the same function, as shown below:
myEmitterIns.on('data',function(e){ console.log(e); }); myEmitterIns.removeListener('data',function(e){ console.log(e); }); myEmitterIns.emit('data','hello data!'); function deal(e){ console.log(e); } myEmitterIns.on('data1',deal); myEmitterIns.removeListener('data1',deal); myEmitterIns.emit('data1','hello data1!');
The execution result is as follows:
E:developmentdocumentnodejsdemo>node event-example.js
hello data!
E:developmentdocumentnodejsdemo>
As can be seen from the execution results, the data event uses an anonymous function, so it is not removed, while the data1 event is successfully unbound. One thing to note here is that after emit triggers an event, all callback functions bound to the event will be called. Even if you use the removeListener function in a callback function to remove another callback, it will be useless, but subsequent The event queue has removed the callback. As shown below:
function dealData1(e){ console.log('data事件执行了...A'); } myEmitterIns.on('data',function(e){ console.log(e); myEmitterIns.removeListener('data',dealData1);//这里解除dealData1的绑定 }); myEmitterIns.on('data',dealData1); myEmitterIns.emit('data','data事件执行了...B'); /*执行结果为: data事件执行了...B data事件执行了...A */ //再次触发该事件时,dealData1回调已经被解除绑定了 myEmitterIns.emit('data','data事件执行了...'); //data事件执行了... 另外可以使用removeAllListeners()解除所有事件的绑定。
6. Get the number of event listeners and listening functions
Use the emitter.listenerCount(eventName) function to get the number of listeners for a specified event. The function emitter.listeners(eventName) can be used to get all the listeners for a specified event. The listening function is used as follows:
var cbA = ()=>{}, cbB = ()=>{}; var emitter = new myEmiter(); emitter.on('data',cbA); emitter.on('data',cbB); console.log('emitter实例的data事件绑定了%d个回调函数',emitter.listenerCount('data')); console.log('它们是:',emitter.listeners('data'));
The execution results are as follows:
E:developmentdocumentnodejsdemo>node event-example.js
The data event of the emitter instance is bound to 2 callback functions
They are: [ [ Function: cbA], [Function: cbB] ]
7. Get and set the maximum number of emitter listeners
nodejs recommends that the number of listeners for the same event should not exceed 10. You can know this by looking at the EventEmitter.defaultMaxListeners property, as follows As shown:
console.log(EventEmitter.defaultMaxListeners);//结果为10个
emitter obtains the maximum number of listeners through the getMaxListeners() method and sets the maximum number of listeners through the setMaxListeners(n) method, as shown below:
var cbA = ()=>{}, cbB = ()=>{}; var emitter = new myEmiter(); emitter.setMaxListeners(1); emitter.on('data',cbA); emitter.on('data',cbB); console.log(emitter.getMaxListeners());
The execution results are as follows:
E:developmentdocumentnodejsdemo>node event-example.js
The maximum number of emitter event listeners is: 1
(node:6808) Warning: Possible EventEmitter memory leak detected. 2 data listener
s added. Use emitter .setMaxListeners() to increase limit
As shown in the above results, if the maximum number of listeners is set, it is best not to exceed the maximum number of listeners for the same event, otherwise it is likely to cause a memory leak.