Home >Web Front-end >JS Tutorial >A brief analysis of Node's events module

A brief analysis of Node's events module

青灯夜游
青灯夜游forward
2023-02-20 19:33:302285browse

A brief analysis of Node's events module

In vue projects, sometimes we use the global event bus to manage communication between components. In the vue2 project, we can use $emit, $on and $off to encapsulate an eventHub; in vue3, $on and $off are removed, we can use mitt library or tiny-emitter library. In node, there is no need to be so troublesome. It has a built-in events module that can help us monitor and emit events.

Event monitoring and emission

First use CommonJS syntax to import the EventEmitter class, and then generate an instance emitter( EventEmitter is very important. For example, the stream that will be introduced in subsequent articles is an instance of EventEmitter):

const EventEmitter = require('events')
const emitter = new EventEmitter()

Then you can use emitter .on() Monitor the event. The first parameter passed in is the event name. The second parameter is the callback to be executed after listening to the event being emitted. If there are incoming parameters when emitting the event, it will be passed For the callback function, you can obtain it one by one, or you can use the remaining parameters of the function as follows: [Recommended related tutorials: nodejs video tutorial, Programming teaching

// 监听事件
emitter.on('test', (...args) => {
  console.log(args) // [ 1, 2, 3 ]
})
// 发射事件
emitter.emit('test', 1, 2, 3)

If you only need to listen to one-time events, you can use

emitter.once():

emitter.once('test', () => {
  console.log('监听到了事件发射')
})

emitter.emit('test')
emitter.emit('test') // 本次发射不会触发打印

If there are multiple places to monitor the event as shown in the following example Once the event is emitted, the listening callbacks will be triggered in order:

emitter.on('test', () => {
  console.log('监听到了事件发射,1')
})
emitter.on('test', () => {
  console.log('监听到了事件发射,2')
})
emitter.emit('test')

Execution results:

A brief analysis of Nodes events module

If you want to add the listening event to the front , you can use

emitter.prependListener() (or emitter.prependOnceListener(), that is, listen in advance but only once):

emitter.on('test', () => {
  console.log('监听到了事件发射,1')
})
emitter.prependListener('test', () => {
  console.log('监听到了事件发射,2')
})

emitter.emit('test')

The current results are as follows:

A brief analysis of Nodes events module

Remove event listening

You can use

emitter.off() (or emitter.removeListener ()) Remove the monitoring of events, but you need to pass in the corresponding event name and callback function, so our callback when monitoring cannot be directly defined in emitter.on()## as above # Internal, you need to define it externally and pass in a reference to the callback: <pre class="brush:js;toolbar:false;">function handler(...args) { console.log(args) // [ 1, 2, 3 ] } emitter.on(&amp;#39;test&amp;#39;, handler) emitter.emit(&amp;#39;test&amp;#39;, 1, 2, 3) emitter.off(&amp;#39;test&amp;#39;, handler) emitter.emit(&amp;#39;test&amp;#39;, &amp;#39;无法被监听到&amp;#39;)</pre>

emitter.off()

Only one listener can be removed, and the listener callback must be passed in. If If you have multiple listeners and want to remove them all, you can use emitter.removeAllListeners(): <pre class="brush:js;toolbar:false;">emitter.on(&amp;#39;test&amp;#39;, handler) emitter.on(&amp;#39;test&amp;#39;, handler) emitter.on(&amp;#39;test&amp;#39;, handler) emitter.removeAllListeners()</pre>

emitter.removeAllListeners()

If no parameters are passed in, then Removes all event listeners for all event names. It can also pass in the event name, and all event listeners corresponding to the event name will be removed.

Some other methods

Limit on the number of listeners1 EventEmitter object, a certain The maximum number of listeners for an event name defaults to 10, which can be verified by

emitter.getMaxListeners()

: <pre class="brush:js;toolbar:false;">console.log(emitter.getMaxListeners()) // 10</pre>For example, it was written 11 times

emitter.on('test ', handler)

, an error will be reported, prompting us to use emitter.setMaxListeners() to increase the maximum limit:

A brief analysis of Nodes events moduleIf we If you want to know how many listeners there are for a certain event name on the current EventEmitter object and whether it exceeds the maximum limit, you can use

emitter.listenerCount()

to pass in the event name to view: <pre class="brush:js;toolbar:false;">console.log(emitter.listenerCount(&amp;#39;test&amp;#39;))</pre>

Get event names and listenersUse

emitter.eventNames()

to get all event names registered on the current EventEmitter object, and the returned Array composed of event strings: <pre class="brush:js;toolbar:false;">emitter.on(&amp;#39;test1&amp;#39;, handler) emitter.on(&amp;#39;test2&amp;#39;, handler) console.log(emitter.eventNames()) // [ &amp;#39;test1&amp;#39;, &amp;#39;test2&amp;#39; ]</pre> If you want to get all the listeners corresponding to an event, you can use

emitter.listeners()

and pass in the event name: <pre class="brush:js;toolbar:false;">function handler1() {} function handler2() {} emitter.on(&amp;#39;test&amp;#39;, handler1) emitter.on(&amp;#39;test&amp;#39;, handler2) console.log(emitter.listeners(&amp;#39;test&amp;#39;))</pre> The results obtained are as follows:

A brief analysis of Nodes events moduleFor more node-related knowledge, please visit:

nodejs tutorial

!

The above is the detailed content of A brief analysis of Node's events module. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete