Home > Web Front-end > JS Tutorial > Detailed explanation of events in Node.js

Detailed explanation of events in Node.js

青灯夜游
Release: 2020-12-01 17:34:01
forward
3136 people have browsed it

Detailed explanation of events in Node.js

Related recommendations: "nodejs Tutorial"

The front-end is certainly no stranger to events, binding the scroll event for the window

window.addEventListener('scroll', ev => {
	console.log(ev);
});
Copy after login

Node.js Most asynchronous operations are event-driven. All objects that can trigger events inherit the EventEmitter class

Event listening

on

Node.js event listening is very similar to jQuery APIemitter.on(eventName, listener)

const ee = new EventEmitter();
ee.on('foo', () => console.log('a'));
Copy after login
  1. EventEmitter instance will maintain a listener array, and each listener defaults Will be added to the end of the array
  2. Every time a listener is added, it will not be checked whether it has been added. Calling on multiple times and passing in the same eventName and listener will cause the listener to be added multiple times

prependListener

emitter.prependListener(eventName, listener)
You can add the listener to the head of the listener array through prependListener

const ee = new EventEmitter();
ee.prependListener('foo', () => console.log('a'));
Copy after login

once

If you want the listener to be triggered once and then no longer trigger, you can use once to bind the event

const ee = new EventEmitter();
ee.once('foo', () => console.log('a'));
Copy after login

Event triggering

emitter.emit(eventName[, ... args])
Most of the developer's event-related work in the browser environment is to subscribe to events, that is, to bind the event processing function listener. In Node.js event programming, it is often necessary to create event objects. The actual trigger event. Use the emit method to synchronously call each listener registered to the event named eventName in the order of listener registration, and pass in the provided parameters

const EventEmitter = require('events');
const myEmitter = new EventEmitter();

// 第一个监听器。
myEmitter.on('event', function firstListener() {
  console.log('第一个监听器');
});
// 第二个监听器。
myEmitter.on('event', function secondListener(arg1, arg2) {
  console.log(`第二个监听器中的事件有参数 ${arg1}、${arg2}`);
});
// 第三个监听器
myEmitter.on('event', function thirdListener(...args) {
  const parameters = args.join(', ');
  console.log(`第三个监听器中的事件有参数 ${parameters}`);
});

console.log(myEmitter.listeners('event'));

myEmitter.emit('event', 1, 2, 3, 4, 5);

// Prints:
// [
//   [Function: firstListener],
//   [Function: secondListener],
//   [Function: thirdListener]
// ]
// 第一个监听器
// 第二个监听器中的事件有参数 1、2
// 第三个监听器中的事件有参数 1, 2, 3, 4, 5
Copy after login

this points to

eventEmitter.emit() The method can pass any number of parameters to the listener. this The keyword will be pointed to the EventEmitter instance bound to the listener

const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
  console.log(a, b, this, this === myEmitter);
  // 打印:
  //   a b MyEmitter {
  //     domain: null,
  //     _events: { event: [Function] },
  //     _eventsCount: 1,
  //     _maxListeners: undefined } true
});
myEmitter.emit('event', 'a', 'b');
Copy after login

You can also use ES6 arrow functions as listeners. But this keyword will not point to the EventEmitter instance:

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  console.log(a, b, this);
  // 打印: a b {}
});
myEmitter.emit('event', 'a', 'b');
Copy after login

Asynchronous call

EventEmitter Call all listeners synchronously in the order of registration, so that To ensure the correct ordering of events, the listener can use the setImmediate() and process.nextTick() methods to switch to asynchronous operation mode

const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
  setImmediate(() => {
    console.log('异步地发生');
  });
});
myEmitter.emit('event', 'a', 'b');
Copy after login

Event unloading

Node.js provides several methods for uninstalling event bindings

off/removeListener

The off method is an alias of the removeListener method and is used to clean up event bindings emitter.removeListener(eventName, listener)

const callback = (stream) => {
  console.log('已连接');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
Copy after login

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

removeAllListeners

emitter. removeAllListeners([eventName])
Remove the listener of the specified eventName event. If eventName is not specified, remove all listeners of the event object. You can get the eventName array on the event object through emitter.eventNames()

const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

myEE.eventNames().forEach(eventName => myEE.removeAllListeners);
Copy after login

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of Detailed explanation of events in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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