Node commonly used built-in modules events event module

table of Contents

1.eventEmitter class

1.1 Various methods of EventEmitter class

2. Detailed explanation of various methods of eventEmitter class

2.1 Binding events (addListener or on) 

2.2 The emit method triggers an event

 2.3 Only bind the event once

2.4 Unbind events

2.5 setMaxListeners specifies the maximum number of event bindings for event handlers

2.6 getMaxListeners Get the maximum number of event bindings for event handlers

2.7 Get all event functions bound by the specified event

3.listenerCount gets the number of handlers for the specified event

4. Events owned by the eventEmitter class itself

4.1 newListener event

4.2 removeEmitter event


1.eventEmitter class

The event module for implementing various types of events.All possible time objects are instances of a subclass that inherits the eventEmitter class.

Usually the eventEmitter class under the event module is used directly

const EventEmitter = require('events').EventEmitter;

// 直接使用EventEmitter类实例
const myEmitter = new EventEmitter;

1.1 Various methods of EventEmitter class

Method name and parameters description
addListener(event,listener) Bind event handlers to specified events
on(event,listener) Bind event handlers to specified events (compared to addListenrer)

once(event,listener)

Execute the event processing function only once for the specified event
removeListener(event,listen) Remove event handler function for specified event
off(event,listen) Remove the event handler function of the specified event (use a little more)
removeAllListens(event) Cancel all event handlers for the specified event
setMaxListeners(n) Set the event handler function that can be bound to the specified event
listeners(event) Get all bound functions of the specified event
emit(event,[arg1],[arg2],[...]) Manually trigger the trigger event

2. Detailed explanation of various methods of eventEmitter class

2.1 Binding events (addListener or on) 

The addListener method is essentially the same as the on method

addListener (event, listen) on (event, listen) accepts two parameters

  1. The first parameter is the name of the bound event
  2. The second parameter is the event handler function
const {EventEmitter} = require("events")
// 定义子类
class Emitter extends EventEmitter{}
// 创建实例
const emitter  = new Emitter()
// 绑定事件
emitter.addListener("con", function() {
    console.log("我是addListener方法")
})
emitter.on("con", function() {
    console.log("我是addListener方法")
})

// 触发事件
emitter.emit('con')

// 事件可以连续触发
emitter.emit('con')
emitter.emit('con')
emitter.emit('con')

Results of the:

2.2 The emit method triggers an event

emit can accept a parameter:

emitter.emit ('play', 'parameter 1', 'parameter 2')

  1. The first parameter is the name of the event that triggered the event (required)
  2. The second parameter and subsequent parameters passed by the event handler function
// 普通触发事件
emitter.emit('someEvents')


// 触发事件的时候传递参数
// 绑定事件
emitter.on("someevent", function () {
    console.log(arguments)   // 打印结果: [Arguments] { '0': '参数1', '1': '参数2' }
})

// 触发事件
emitter.emit('play','参数1','参数2')

 2.3 Only bind the event once

The once-bound event will only be executed once, and will be automatically unbound after the execution is completed

const {EventEmitter} = require("events")
// 定义子类
class Emitter extends EventEmitter{}
// 创建实例
const emitter  = new Emitter()
// 绑定事件
emitter.once('play',function() {
    console.log("我是play方法>_<")
})
//执行事件
emitter.emit('play');

//多次执行事件
emitter.emit('play');
emitter.emit('play');

Execution result (the event is still executed only once after multiple execution events)

2.4 Unbind events

When binding events, the same event name can bind multiple events

  1. removeListener
  2. offListener
  3. removeAllListeners

1.removeListener (event,listener)

Accepts two parameters:

  1. The first parameter is the specified event name
  2. The second parameter is to specify the event handler function that needs to be unbound

removeListener() At most, only one listener will be removed from the listener array. If the listener is added to the specified  eventName listener array multiple times, it must be called multiple times  removeListener() to remove all instances.

Once the event is triggered, all the listeners bound to the event will be called in sequence. This means that after an event is triggered, and the last execution prior to the completion of a listener,  removeListener() or  removeAllListeners() not from  emit() removing them.

 

//绑定事件
emitter.on("play",foo1);
emitter.on("play",foo2);
emitter.on("play",foo3);

function foo1() {
    console.log('我是foo1');
}
function foo2() {
    console.log('我是foo2');
}
function foo3() {
    console.log('我是foo3');
}

//触发事件
setInterval(()=> {
    emitter.emit('play');
},1000)

//设置3s之后解绑foo2
setInterval(()=> {
    emitter.removeListener("play",foo2);
},3000);

The effect of the implementation is as follows:

In powerShell, you can stop the execution of the event through the "ctrl + c" class 

2. The off method releases the event function of the specified event

Similar to the removeListener method, also accepts two parameters

There is no essential difference from the removeListener method, only the method name is different

emitter.off("play",foo2);

3. removeAllLIsteners removes all event handlers bound under the specified event name

Accepts a parameter as: the specified event name

After 5s, cancel all the bound event functions

setInterval(()=> {
    emitter.removeAllListeners("play");
},5000);

If the removeAllListeners method does not pass parameters, it means that all event processing functions under the name of all events are unbound

2.5 setMaxListeners specifies the maximum number of event bindings for event handlers

By default, if you add more than for specific events  10 a listener, it  EventEmitter will print a warning. This helps to discover memory leaks. However, not all events require  10 a listener. emitter.setMaxListeners() The method can EventEmitter modify the limit for the specified  instance. The value set to  Infinity(or  0) means that the number of listeners is not limited.

By default, the same event name can be bound with up to 10 event handlers, or it can be modified through setMaxListeners

// 设置最大事件处理函数绑定个数
emitter.setMaxListeners(12)

It is worth noting:

  1. If more than 10 event handler functions are bound to the same event name, there will be a prompt and the program will still execute
  2. If the maximum number of event processing functions is greater than or equal to the number of binding events, there will be no prompt error

2.6 getMaxListeners Get the maximum number of event bindings for event handlers

console.log(emitter.getMaxListeners());

The printed result is the 12 I set before

2.7 Get all event functions bound by the specified event

console.log(emitter.listeners('play'));

The printed result is an array

3.listenerCount gets the number of handlers for the specified event

This method accepts two parameters

  1. The first parameter is the instance object of the binding event
  2. The second parameter is the name of the bound event
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(EventEmitter.listenerCount(myEmitter, 'event'));
// Prints: 2

4. Events owned by the eventEmitter class itself

4.1 newListener event

All subclass instance objects that inherit the EventEmitter class will trigger newListener events when they are bound to event handlers.

EventEmitter The instance triggers its own 'newListener' event before the new listener is added to its internal listener array  .

'newListener' The listener registered for the  event will pass the event name and a reference to the listener to be added.

The fact that the event is triggered before the listener is added has subtle but important side effects:  any other listeners 'newListener' registered to the same in the  callback  namewill be inserted before the listener being added.

 

const {EventEmitter} = require("events");
// 定义子类
class emitter extends EventEmitter{};
// 创建实例
const myEmitter = new emitter();
// 只处理一次,避免无限循环。
myEmitter.once('newListener', (event, listener) => {
    if (event === 'event') {
        // 在前面插入一个新的监听器。
        myEmitter.on('event', () => {
            console.log('B');
        });
    }
});
myEmitter.on('event', () => {
    console.log('A');
});
myEmitter.emit('event');
// 打印:
//   B
//   A

4.2 removeEmitter event

When the event handler function is canceled for the subclass instance object inheriting EventEmitter class, the removeListener event will be triggered

The removeListener event is triggered after the listener is removed.

Accepts two parameters:

The first parameter is the specified event name

The second parameter is the event function that needs to be unbound

// 绑定事件
emitter.on("someevent", fn1)
emitter.on("someevent", fn2)
emitter.on("newevent", fn2)

// 事件处理函数
function fn1() {
    console.log("someevent fn1")
}
function fn2() {
    console.log("someevent fn2")
}

emitter.removeListener("someevent", fn1)  // 每次取消事件绑定都会执行removeListener事件

 

In my article, I only briefly introduced some of the more commonly used events, and there are still many that are not mentioned.If you want to learn more, go to the official website of node to read the document.

 

 

Published 34 original articles · received 145 · views 7184

Guess you like

Origin blog.csdn.net/lhrdlp/article/details/105484996