Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What objects are provided by the event module in nodejs

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about what objects are provided by the event module in nodejs. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

In nodejs, the event module "events" provides only one object "EventEmitter", and its core is event emission and event listeners. The object supports several event listeners; when the event is emitted, the event listeners registered to the event are called in turn, and the event parameters are passed as callback function parameters.

The operating environment of this tutorial: windows7 system, nodejs 12.19.0, Dell G3 computer.

Event module in nodejs (events)

Events is the most important module of node.js, and the events module provides only one object. The core of events.EventEmitter,EventEmitter is event emission and event listener.

Most of the modules in Node.js are inherited from Event modules.

Unlike events on the DOM tree, there is no event bubbling, layer-by-layer capture, and so on.

EventEmitter supports several event listeners. When an event is emitted, the event listeners registered to the event are called in turn, and the event parameters are passed as callback function parameters.

How to access:

Require ('events'); emitter.on (event, listener) / * call the events module to get the events.EventEmitter object * / var EventEmitter = require (' events'). EventEmitter; var ee = new EventEmitter () / * EventEmitter.on (event, listener) registers a listening parameter 1:event string for the event. Event name parameter 2: callback function * / ee.on ('some_events', function (foo, bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);}); console.log (' first round'); ee.emit ('some_events',' Wilson', 'Zhong') Console.log ('second round'); ee.emit ('some_events',' Wilson','Z'); emitter.emit (event, [arg1], [arg2], [...])

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); ee.on (' some_events', function (foo, bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);}); / * EventEmitter.emit (event, [arg1], [arg2], [...]) Trigger the specified event parameter 1:event string, event name parameter 2: optional parameter, pass in the callback function parameter return value sequentially: whether the event is listening * / var isSuccess = ee.emit ('some_events',' Wilson', 'Zhong') Ee.on ('some_events', function (foo, bar) {console.log ("2nd listening event, parameter foo=" + foo + ", bar=" + bar);}); ee.emit (' some_events', 'zhong',' wei'); var isSuccess2 = ee.emit ('other_events',' Wilson', 'Zhong'); console.log (isSuccess); console.log (isSuccess2)

The example triggers the event three times. Some_events registers listening, and the emit function returns a true when it is called, while other_events does not register listening. The emit function returns a false, indicating that the event is not listening. Of course, you can ignore the return value!

Emitter.once (event, listener)

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); / * EventEmitter.once (event, listener) registers one-time listening for the event, and removes the listening parameter 1:event string after triggering once. Event name parameter 2: callback function * / ee.once (' some_events', function (foo, bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);}) Console.log ('first round'); ee.emit ('some_events',' Wilson', 'Zhong'); console.log (' second round'); var isSuccess = ee.emit ('some_events',' Wilson', 'Zhong'); console.log (isSuccess)

As can be seen from the execution result of the above sample code, after registering a monitor for some_events with emitter.once, it is triggered by calling emitter.emit in two rounds, and the second round will return false;, which indicates that there is a slight difference between registering listening with emitter.once and registering listening with emitter.on mentioned earlier.

Emitter.once registration monitoring is an one-time monitoring, when triggered once, the monitoring will be removed! Of course, it is more obvious from the name ^ _ ^!

Emitter.removeListener (event, listener)

First, let's take a look at a failure scenario.

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); ee.on (' some_events', function (foo, bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);}) / * when I saw the removeListener removal method in API, I thought it should be like this, but the result was ^ _ ^! * / ee.removeListener ('some_events', function () {console.log (' successfully removed event some_events snooping!');}); console.log ('first round'); ee.emit ('some_events',' Wilson', 'Zhong')

When I registered a monitor for some_events with emitter.on, I used emiiter.removeListener to remove some_events listening, then called emitter.emit to trigger it, and found that it didn't work as I expected! Why?

I take it for granted that the second parameter of emiiter.removeListener is a callback function, so API should read it carefully!

Let's take another look at a successful scenario.

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); var listener = function (foo,bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);} var listener2= function (foo,bar) {console.log ("second listening event, parameter foo=" + foo + ", bar=" + bar) } var listener3= function (foo,bar) {console.log ("3rd listening event, parameter foo=" + foo + ", bar=" + bar);} ee.on ('some_events', listener); ee.on (' some_events', listener2); ee.on ('some_events', listener3) / * EventEmitter.removeListener (event, listener) remove the listener for the specified event Note: the listener must be a registered PS: it will fail after the previous example, largely because it ignores the listener and takes it for granted that passing an event name is OK, so it is tragic! * / ee.removeListener ('some_events', listener); ee.removeListener (' some_events', listener3) Ee.emit ('some_events',' Wilson', 'Zhong')

I use the example to add three listeners to some_events, remove the first and third listeners, and finally use emitter.emit to trigger some_events. It is not difficult to find that the first and third listeners removed with emitter.removeListener no longer work.

Of course, harmfully, the second parameter of emitter.removeListener is the listener to be removed, not the callback function after the removal is successful. ^ _ ^!

Emitter.removeAllListeners ([event])

Emitter.removeListener has been used, but an event can have multiple listeners, and when all of them need to be removed, it is obviously not pleasant to remove them one by one, which is not in line with the nature of laziness!

Let's experience the convenience of emitter.removeAllListeners!

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); var listener = function (foo,bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);} var listener2= function (foo,bar) {console.log ("second listening event, parameter foo=" + foo + ", bar=" + bar);} ee.on (' some_events', listener); ee.on ('some_events', listener2) Ee.on ('other_events',function (foo,bar) {console.log ("other listening events, parameters foo=" + foo + ", bar=" + bar);}); / * EventEmitter.removeAllListeners ([event]) remove (approve event) all listener parameters 1: optional parameter, event string, event name * / ee.removeAllListeners (' some_events'); ee.emit ('some_events',' Wilson', 'Zhong') Ee.emit ('other_events',' Wilson', 'Zhong')

Looking at the results of the above execution, you will find that two listeners have been registered with some_events; one has been registered with other_events; and I have passed the some_events event name by calling emitter.removeAllListeners

Finally, the some_events and other_events events are triggered by the emitter.on function, and it is found that the two listeners registered by some_events do not exist, while the listeners registered by other_events still exist.

This means that when emitter.removeAllListeners passes an event name as a parameter, it removes all listeners from the incoming event name without affecting other event listeners!

Emitter.removeAllListeners may not pass the event name parameter; it can be executed directly

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); var listener = function (foo,bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);} var listener2= function (foo,bar) {console.log ("second listening event, parameter foo=" + foo + ", bar=" + bar);} ee.on (' some_events', listener); ee.on ('some_events', listener2) Ee.on ('other_events',function (foo,bar) {console.log ("other listening events, parameters foo=" + foo + ", bar=" + bar);}); / * EventEmitter.removeAllListeners ([event]) removes (approved event) all listener parameters 1: optional parameter, event string, event name * / ee.removeAllListeners (); ee.emit (' some_events', 'Wilson',' Zhong') Ee.emit ('other_events',' Wilson', 'Zhong')

The sample code is almost the same as when passing in parameters, except that the specified event name is not passed in when calling emitter.removeAllListeners

The result of the run will find that all some_events and other_events listeners no longer exist, it will remove all listeners! (more violent methods should generally be used with caution.)

Emitter.listeners (event)

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); var listener = function (foo,bar) {console.log ("first listening event, parameter foo=" + foo + ", bar=" + bar);} var listener2= function (foo,bar) {console.log ("second listening event, parameter foo=" + foo + ", bar=" + bar);} ee.on (' some_events', listener); ee.on ('some_events', listener2) Ee.on ('other_events',function (foo,bar) {console.log ("other listening events, parameters foo=" + foo + ", bar=" + bar);}); / * EventEmitter.listeners (event) / / returns the listening array parameter 1:event string of the specified event, event name * / var listenerEventsArr = ee.listeners (' some_events'); console.log (listenerEventsArr.length) for (var I = listenerEventsArr.length-1; I > = 0 ) {console.log (listenerEventsArr [I]);}

Register two listeners to some_events, call the emitter.listeners function, pass in the some_events event name, and receive the value returned by the function

As you can see from the result, the return value receives a collection of all registered listeners from some_events!

Emitter.setMaxListeners (n)

It is true that multiple listeners can be added to an event, but what is the default maximum value of Nodejs?

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); / * add 11 listeners to EventEmitter * / for (var I = 10; I > = 0; iMub -) {ee.on (' some_events',function () {console.log ('th'+ (I + 1) + 'listeners');});}

Add N monitoring sample source codes

In the above example, I use a loop to add 11 listeners to some_events, execute the code, and find that the warning message appears, and the prompt is more detailed. I need to use emitter.setMaxListeners () to raise the limit.

Var EventEmitter = require ('events'). EventEmitter; var ee = new EventEmitter (); / * EventEmitter.setMaxListeners (n) set the maximum listening parameter 1: n to EventEmitter. When the maximum number of listeners exceeds 10, the maximum number of listeners without setting EventEmitter will prompt: (node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners () to increase limit. The designer thinks that too many listeners may cause memory leaks, so there is such a warning * / ee.setMaxListeners (15); / * add 11 listeners to EventEmitter * / for (var I = 10; I > = 0; iMuk -) {ee.on ('some_events',function () {console.log (' th'+ (I + 1) + 'listeners');});})

When I call emitter.setMaxListeners and pass in 15:00, execute the code, and the warning message no longer appears

The function of emitter.setMaxListeners is to set the maximum number of listeners for EventEmitter. It feels like there is generally no need to set this value, and there should be fewer cases where 10 are not enough.

The designer thought that too many listeners would lead to memory leaks, so they gave a warning!

Others.

If you use less, I won't go into details.

EventEmitter.defaultMaxListeners

EventEmitter.defaultMaxListeners function is similar to setMaxListeners.

Set maximum listening for all EventEmitter

SetMaxListeners priority is higher than defaultMaxListeners

EventEmitter.listenerCount (emitter, event)

Returns the number of listeners for the specified event

Special event Error

Quote from the Node.js Development Guide: EventEmitter defines a special event error that contains the semantics of "error". We usually emit error events when we encounter an exception. When error is launched, EventEmitter specifies that if there is no responsive listener, Node.js will treat it as an exception, exit the program and print the call stack. We usually set up listeners for objects that emit error events to avoid crashing the whole program after encountering an error.

Inheritance of events

Thank you for reading! This is the end of the article on "what objects are provided by the event module in nodejs". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report