A brief analysis of Node's events module

青灯夜游
Release: 2023-02-21 19:43:28
forward
2173 people have browsed it

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,$onand$offto encapsulate aneventHub; in vue3,$onand$offare 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 theEventEmitterclass, and then generate an instanceemitter(EventEmitteris very important. For example, thestreamthat will be introduced in subsequent articles is an instance ofEventEmitter):

const EventEmitter = require('events') const emitter = new EventEmitter()
Copy after login

Then you can useemitter .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 thefunction 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)
Copy after login

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') // 本次发射不会触发打印
Copy after login

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')
Copy after login

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()(oremitter.prependOnceListener(), that is, listen in advance but only once):

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

The current results are as follows:

A brief analysis of Nodes events module

Remove event listening

You can use

emitter.off()(oremitter.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 inemitter.on()## as above # Internal, you need to define it externally and pass in a reference to the callback:

function handler(...args) { console.log(args) // [ 1, 2, 3 ] } emitter.on('test', handler) emitter.emit('test', 1, 2, 3) emitter.off('test', handler) emitter.emit('test', '无法被监听到')
Copy after login

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 useemitter.removeAllListeners():

emitter.on('test', handler) emitter.on('test', handler) emitter.on('test', handler) emitter.removeAllListeners()
Copy after login

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()

:

console.log(emitter.getMaxListeners()) // 10
Copy after login
For example, it was written 11 times

emitter.on('test ', handler)

, an error will be reported, prompting us to useemitter.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:

console.log(emitter.listenerCount('test'))
Copy after login

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:

emitter.on('test1', handler) emitter.on('test2', handler) console.log(emitter.eventNames()) // [ 'test1', 'test2' ]
Copy after login
If you want to get all the listeners corresponding to an event, you can use

emitter.listeners()

and pass in the event name:

function handler1() {} function handler2() {} emitter.on('test', handler1) emitter.on('test', handler2) console.log(emitter.listeners('test'))
Copy after login
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!

Related labels:
source:juejin.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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!