Home > Web Front-end > Front-end Q&A > Which object is provided by the event module in nodejs

Which object is provided by the event module in nodejs

青灯夜游
Release: 2021-11-11 16:50:29
Original
1535 people have browsed it

In nodejs, the event module "events" only provides one object "EventEmitter", whose core is event emission and event listener. This object supports several event listeners; when an event is emitted, the event listeners registered to this event are called in sequence, and the event parameters are passed as callback function parameters.

Which object is provided by the event module in nodejs

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

Event module (events) in nodejs

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

Most modules in Node.js inherit from the Event module.

Different from events on the DOM tree, there is no event bubbling or layer-by-layer capture.

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

How to access:

require('events');
Copy after login

emitter.on(event, listener)

/*
    调用events模块,获取events.EventEmitter对象
*/
var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();

/*
    EventEmitter.on(event, listener) 为事件注册一个监听
    参数1:event  字符串,事件名
    参数2:回调函数
*/
ee.on('some_events', function(foo, bar) {
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
});

console.log('第一轮');
ee.emit('some_events', 'Wilson', 'Zhong');

console.log('第二轮');
ee.emit('some_events', 'Wilson', 'Z');
Copy after login

emitter.emit(event, [arg1], [arg2], [...])

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

ee.on('some_events', function(foo, bar) {         
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
});/*
    EventEmitter.emit(event, [arg1], [arg2], [...])   触发指定事件
    参数1:event  字符串,事件名
    参数2:可选参数,按顺序传入回调函数的参数
    返回值:该事件是否有监听*/var isSuccess = ee.emit('some_events', 'Wilson', 'Zhong');

ee.on('some_events', function(foo, bar) {         
    console.log("第2个监听事件,参数foo=" + foo + ",bar="+bar );
});

ee.emit('some_events', 'zhong', 'wei');var isSuccess2 = ee.emit('other_events', 'Wilson', 'Zhong');

console.log(isSuccess);
console.log(isSuccess2);
Copy after login

The example performs three trigger event operations, in which some_events is registered for monitoring, and the emit function will return an true, and other_events has not registered a listener, the emit function will return a false, indicating that the event is not monitored; of course, you can also ignore this return value!

emitter.once(event, listener)

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();/*
    EventEmitter.once(event, listener)  为事件注册一次性监听,触发一次后移除监听
    参数1:event  字符串,事件名
    参数2:回调函数*/ee.once('some_events', function(foo, bar) {
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
});


console.log('第一轮');
ee.emit('some_events', 'Wilson', 'Zhong');

console.log('第二轮');var isSuccess =  ee.emit('some_events', 'Wilson', 'Zhong');
console.log(isSuccess);
Copy after login

As can be seen from the execution results of the above example code, using emitter.once After registering a listener for some_events, call emitter.emit trigger in two rounds, and the second round will return false; this means that registering a monitor with emitter.once is slightly different from registering a monitor with emitter.on mentioned earlier,

emitter.once registered monitoring is a one-time monitoring. When triggered once, the monitoring will be removed! Of course, it’s more obvious from the name^_^!

emitter.removeListener(event, listener)

Let’s first look at a failed one Scenario~~~

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

ee.on('some_events', function(foo, bar) {
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
});/*
    看到API中removeListener移除方法时,以为应该是这样
    但是结果^_^!!!!!*/ee.removeListener('some_events', function(){
    console.log('成功移除事件some_events监听!');        
});

console.log('第一轮');
ee.emit('some_events', 'Wilson', 'Zhong');
Copy after login

After I used emitter.on to register a listener for some_events, I used emiiter.removeListener to remove the listener for some_events, and then I called emitter.emit to trigger it, and finally found that it was not going as I imagined! why?

I take it for granted that the second parameter of emiiter.removeListener is a callback function. The API still needs to be read carefully! ! !

Let’s look at a successful scene~~~

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();var listener = function(foo,bar)
{
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
}var listener2= function(foo,bar)
{
    console.log("第2个监听事件,参数foo=" + foo + ",bar="+bar );
}var listener3= function(foo,bar)
{
    console.log("第3个监听事件,参数foo=" + foo + ",bar="+bar );
}

ee.on('some_events', listener);

ee.on('some_events', listener2);

ee.on('some_events', listener3);/*
    EventEmitter.removeListener(event, listener)  移除指定事件的监听器
    注意:该监听器必须是注册过的
    PS:上一个例子之后以会失败,很大原因就是忽略了监听器,理所当然的认为传个事件名就OK了,所以就悲剧了!*/ee.removeListener('some_events', listener);

ee.removeListener('some_events', listener3);

ee.emit('some_events', 'Wilson', 'Zhong');
Copy after login

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

Of course it is harmful. It turns out that 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. When all need to be removed, removing them one by one is obviously not a pleasant approach and does not comply with Lazy nature!

Let us experience the convenience brought by emitter.removeAllListeners!

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();var listener = function(foo,bar)
{
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
}var listener2= function(foo,bar)
{
    console.log("第2个监听事件,参数foo=" + foo + ",bar="+bar );
}

ee.on('some_events', listener);

ee.on('some_events', listener2);

ee.on('other_events',function(foo,bar)
{
    console.log("其它监听事件,参数foo=" + foo + ",bar="+bar );
});/*
    EventEmitter.removeAllListeners([event])   移除(批定事件)所有监听器
    参数1:可选参数,event  字符串,事件名*/ee.removeAllListeners('some_events');

ee.emit('some_events', 'Wilson', 'Zhong');

ee.emit('other_events', 'Wilson', 'Zhong');
Copy after login

Look at the above execution results, you will find that some_events Two listeners were registered; one listener was registered for other_events; I called emitter.removeAllListeners and passed the some_events event name;

Finally used the emitter.on function to trigger two events, some_events and other_events, and finally found that the two events registered by some_events None of the listeners exist, but the listeners registered by other_events still exist;

This means that when emitter.removeAllListeners passes the event name as a parameter, all listeners with the passed event name are removed without affecting other Event monitoring!

emitter.removeAllListeners can be executed directly without passing the event name parameter.

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();var listener = function(foo,bar)
{
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
}var listener2= function(foo,bar)
{
    console.log("第2个监听事件,参数foo=" + foo + ",bar="+bar );
}

ee.on('some_events', listener);

ee.on('some_events', listener2);

ee.on('other_events',function(foo,bar)
{
    console.log("其它监听事件,参数foo=" + foo + ",bar="+bar );
});/*
    EventEmitter.removeAllListeners([event])   移除(批定事件)所有监听器
    参数1:可选参数,event  字符串,事件名*/ee.removeAllListeners();

ee.emit('some_events', 'Wilson', 'Zhong');

ee.emit('other_events', 'Wilson', 'Zhong');
Copy after login

示例代码和传入参数时几乎一样,只是在调用emitter.removeAllListeners并没有传入指定事件名;

运行结果会发现some_events和other_events所有监听都不存在了,它会移除所有监听!(比较暴力的方法一般要慎用~~)

emitter.listeners(event)

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();var listener = function(foo,bar)
{
    console.log("第1个监听事件,参数foo=" + foo + ",bar="+bar );
}var listener2= function(foo,bar)
{
    console.log("第2个监听事件,参数foo=" + foo + ",bar="+bar );
}

ee.on('some_events', listener);

ee.on('some_events', listener2);

ee.on('other_events',function(foo,bar)
{
    console.log("其它监听事件,参数foo=" + foo + ",bar="+bar );
});/*
    EventEmitter.listeners(event)   //返回指定事件的监听数组
    参数1:event  字符串,事件名    
*/var listenerEventsArr = ee.listeners('some_events');

console.log(listenerEventsArr.length)for (var i = listenerEventsArr.length - 1; i >= 0; i--) {
    console.log(listenerEventsArr[i]); 
};
Copy after login

给some_events注册两个监听,调用emitter.listeners函数,传入some_events事件名,接收函数返回值;

从结果可以看出,返回值接收到some_events所有注册监听的集合!

emitter.setMaxListeners(n)

一个事件可以添加多个监听是没错,但Nodejs默认最大值是多少呢?

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();/*
     给EventEmitter 添加11个监听*/for (var i = 10; i >= 0; i--) {
    ee.on('some_events',function()
    {
        console.log('第'+ (i +1) +'个监听');
    });
};
Copy after login

添加N个监听示例源码

上面示例中我用个循环给some_events添加11个监听,执行代码,发现warning信息出现,并且提示的比较详细了,需要用emitter.setMaxListeners()去提升限值

var EventEmitter = require('events').EventEmitter;   
var ee = new EventEmitter();/*
    EventEmitter.setMaxListeners (n)   给EventEmitter设置最大监听
    参数1: n 数字类型,最大监听数
    
    超过10个监听时,不设置EventEmitter的最大监听数会提示:
    (node) warning: possible EventEmitter memory leak detected. 11 listeners added.
     Use emitter.setMaxListeners() to increase limit.
    设计者认为侦听器太多,可能导致内存泄漏,所以存在这样一个警告*/ee.setMaxListeners(15);/*
     给EventEmitter 添加11个监听*/for (var i = 10; i >= 0; i--) {
    ee.on('some_events',function()
    {
        console.log('第'+ (i +1) +'个监听');
    });
};
Copy after login

当我调用emitter.setMaxListeners传入15时,执行代码,warning信息不再出现;

emitter.setMaxListeners的作用是给EventEmitter设置最大监听数,感觉一般是不需要设置这个值,10个还不够用的情况应该是比较少了!

设计者认为侦听器太多会导致内存泄漏,所有就给出了一个警告!

其它...

 用的比较少的就不详细说了

EventEmitter.defaultMaxListeners

EventEmitter.defaultMaxListeners功能与setMaxListeners类似,
给所有EventEmitter设置最大监听
setMaxListeners优先级大于defaultMaxListeners

EventEmitter.listenerCount(emitter, event)

返回指定事件的监听数

 特殊的事件Error

引用自Node.js开发指南:EventEmitter 定义了一个特殊的事件 error,它包含了“错误”的语义,我们在遇到 异常的时候通常会发射 error 事件。当 error 被发射时,EventEmitter 规定如果没有响 应的监听器,Node.js 会把它当作异常,退出程序并打印调用栈。我们一般要为会发射 error 事件的对象设置监听器,避免遇到错误后整个程序崩溃。

事件的继承

以后归到util里再讲一下吧,有兴趣的可以自已看看 http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor

【推荐学习:《nodejs 教程》】

The above is the detailed content of Which object is provided by the event module in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template