Follow me to learn Nodejs (2) the node. js event module

  • 2020-03-30 03:01:36
  • OfStack

Introduction and information

(link: http://nodejs.org/api/events.html)

(link: http://www.infoq.com/cn/articles/tyq-nodejs-event)

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

      Most of the modules in node. js inherit from the Event module.

      Unlike events in the DOM tree, there is no bubbling, layer - by - layer trapping behavior.

  How to access:


require('events');

Emitter. On (event listener)

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452191711763.png? 201442191725 ">  



var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();

ee.on('some_events', function(foo, bar) {
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
});
console.log(' The first round ');
ee.emit('some_events', 'Wilson', 'Zhong');
console.log(' The second round ');
ee.emit('some_events', 'Wilson', 'Z');
EventEmitter.on(event, listener)  The sample source code 

Emitter. Emit (event, (arg1), [arg2], [...]. )

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452191818868.png? 201442191835 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();
ee.on('some_events', function(foo, bar) {         
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
});

var isSuccess = ee.emit('some_events', 'Wilson', 'Zhong');
ee.on('some_events', function(foo, bar) {         
    console.log(" The first 2 Monitor events , 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);
emitter.emit(event, [arg1], [arg2], [...])  The sample source code 

The example has three trigger event operations, among which some_events registers the listener, the emit function will return a true when called, while other_events does not register the listener, the emit function will return a false, indicating that the event is not listened to. You don't have to worry about the return value!

Emitter. Once (event listener)

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452191900580.png? 201442191917 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();

ee.once('some_events', function(foo, bar) {
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
});
console.log(' The first round ');
ee.emit('some_events', 'Wilson', 'Zhong');
console.log(' The second round ');
var isSuccess =  ee.emit('some_events', 'Wilson', 'Zhong');
console.log(isSuccess);
emitter.once(event, listener)  The sample source code 

      From the execution results of the above sample code, it can be seen that after registering a listener with emp.once to some_events, the emp.emit will be fired in two rounds, and false will be returned in the second round. So that means that email.once is a little bit different than email.on,

      Emitter. Once registered listener is a one-time listener, and when triggered once, the listener is removed! Of course, it's obvious from the name.

Emitter. RemoveListener (event listener)

  Let's start with a failure scenario

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452191940138.png? 20144219203 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();
ee.on('some_events', function(foo, bar) {
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
});

ee.removeListener('some_events', function(){
    console.log(' Successfully removed event some_events Listening to the !');        
});
console.log(' The first round ');
ee.emit('some_events', 'Wilson', 'Zhong');
emitter.removeListener(event, listener)  Example failure scenario source code 

      When I registered a monitor for some_events with emm. on, I used emiiter. RemoveListener to remove the monitor for some_events, and then called emm. emit to trigger it. Finally, I found that it was not happening as I expected! Why?

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

Now let's look at another successful scenario ~ ~ ~

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452192044390.png? 201442192058 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();
var listener = function(foo,bar)
{
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
}
var listener2= function(foo,bar)
{
    console.log(" The first 2 Monitor events , parameter foo=" + foo + ",bar="+bar );
}
var listener3= function(foo,bar)
{
    console.log(" The first 3 Monitor events , parameter foo=" + foo + ",bar="+bar );
}
ee.on('some_events', listener);
ee.on('some_events', listener2);
ee.on('some_events', listener3);

ee.removeListener('some_events', listener);
ee.removeListener('some_events', listener3);
ee.emit('some_events', 'Wilson', 'Zhong');
emitter.removeListener(event, listener)  Example success scenario source code 

      I used the method in the example to add three listeners to some_events and remove the first and third listeners. Finally, I used emp. emit to trigger some_events. The output result is not difficult to find that the first and third listeners removed by emm. removeListener did not work again.

      The second argument to the original emitter. RemoveListener is the listener to be removed, not the callback function after successful removal... ^_^!

Emitter. RemoveAllListeners ([event])

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

Let's experience the emitter. RemoveAllListeners bring convenient!

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452192136498.png? 201442192153 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();
var listener = function(foo,bar)
{
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
}
var listener2= function(foo,bar)
{
    console.log(" The first 2 Monitor events , 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 , parameter foo=" + foo + ",bar="+bar );
});

ee.removeAllListeners('some_events');
ee.emit('some_events', 'Wilson', 'Zhong');
ee.emit('other_events', 'Wilson', 'Zhong');
emitter.removeAllListeners  Pass in the event name parameter sample source code 

      Looking at the execution results above, you will see that you have registered two listeners for some_events; Register a listener for other_events; I call emitter some_events removeAllListeners pass the event name;

      Finally, the emp.on function was used to trigger two events, some_events and other_events. Finally, it was found that the two listeners registered by some_events did not exist, while the listener registered by other_events still existed.

      . This means that when the emitter removeAllListeners event name is used as a parameter, when introduced into the event name to remove all listening, but will not affect other event listeners!

Emitter. RemoveAllListeners can not pass with the event name parameters; Direct execution

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452192222778.png? 201442192236 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();
var listener = function(foo,bar)
{
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
}
var listener2= function(foo,bar)
{
    console.log(" The first 2 Monitor events , 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 , parameter foo=" + foo + ",bar="+bar );
});

ee.removeAllListeners();
ee.emit('some_events', 'Wilson', 'Zhong');
ee.emit('other_events', 'Wilson', 'Zhong');
emitter.removeAllListeners  Do not pass the parameter sample source 

      Sample code and the incoming parameters are nearly the same, just the call emitter. RemoveAllListeners didn't introduced to the specified event name;

      When you run some_events and other_events, you will find that all the listeners are gone, and it will remove all the listeners! (more violent methods should be used with caution ~~)

Emitter. Listeners (event)

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452192302594.png? 201442192316 ">


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();
var listener = function(foo,bar)
{
    console.log(" The first 1 Monitor events , parameter foo=" + foo + ",bar="+bar );
}
var listener2= function(foo,bar)
{
    console.log(" The first 2 Monitor events , 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 , parameter foo=" + foo + ",bar="+bar );
});
/*
    EventEmitter.listeners(event)   //Returns a listener array for the specified event
     parameter 1 : event   String, event name     
*/
var listenerEventsArr = ee.listeners('some_events');
console.log(listenerEventsArr.length)
for (var i = listenerEventsArr.length - 1; i >= 0; i--) {
    console.log(listenerEventsArr[i]); 
};
emitter.listeners(event)  The sample source code 

      Register two listeners to some_events, call emp.listeners function, pass in the event name of some_events, and receive the return value of the function;

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

Emitter. SetMaxListeners (n)

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

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452192337691.png? 201442192353 ">  


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();

for (var i = 10; i >= 0; i--) {
    ee.on('some_events',function()
    {
        console.log(' The first '+ (i +1) +' A listener ');
    });
};
 add N Monitor sample source code 

In the above example, I used a loop to add 11 listeners to some_events, executed the code, and found that the warning message appeared, and the hints were more detailed, so I needed to use emp.setmaxlisteners () to raise the limit

< img border = 0 id = theimg onclick = window. The open this. (SRC) SRC = "/ / files.jb51.net/file_images/article/201405/201452192414399.png? 201442192428 ">


var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();

ee.setMaxListeners(15);

for (var i = 10; i >= 0; i--) {
    ee.on('some_events',function()
    {
        console.log(' The first '+ (i +1) +' A listener ');
    });
};
emitter.setMaxListeners  The sample source code 

      When I call emp.setmaxlisteners and pass in 15, the code is executed, and the warning message no longer appears.

      Emp. setMaxListeners is used to set the maximum number of listeners for EventEmitter. It seems that this value is usually not necessary, and it is rare that 10 is not enough!

      The designer thinks that too many listeners can cause memory leaks, so that's a warning!

The other...

  I'm not going to go into the details of the less used ones

EventEmitter. DefaultMaxListeners

      Similar to setMaxListeners EventEmitter. DefaultMaxListeners function,
      Set a maximum listener for all EventEmitter
      The setMaxListeners have a higher priority than the defaultMaxListeners

EventEmitter. ListenerCount (emitter, the event)

      Returns the number of listeners for the specified event

  Special event Error

      From the node. js development guide: EventEmitter defines a special event error that contains the semantics of "error" and is usually emitted when an exception is encountered. When an error is emitted, 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. Generally, we should set up a listener for the object that will emit error events to avoid the crash of the whole program after encountering errors.

Inheritance of events

      Speak once again in the later go to util, interested can see for yourself at http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor


Related articles: