Node.js 事件触发器

¥The Node.js Event emitter

如果你在浏览器中使用 JavaScript,你就会知道有多少用户交互是通过事件处理的:鼠标单击、键盘按钮按下、对鼠标移动做出反应等。

¥If you worked with JavaScript in the browser, you know how much of the interaction of the user is handled through events: mouse clicks, keyboard button presses, reacting to mouse movements, and so on.

在后端,Node.js 为我们提供了使用 events 模块 构建类似系统的选项。

¥On the backend side, Node.js offers us the option to build a similar system using the events module.

这个模块特别提供了 EventEmitter 类,我们将使用它来处理事件。

¥This module, in particular, offers the EventEmitter class, which we'll use to handle our events.

你使用以下方法初始化它:

¥You initialize that using

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

此对象公开了 onemit 方法等。

¥This object exposes, among many others, the on and emit methods.

  • emit 用于触发事件

    ¥emit is used to trigger an event

  • on 用于添加在触发事件时要执行的回调函数

    ¥on is used to add a callback function that's going to be executed when the event is triggered

例如,让我们创建一个 start 事件,作为示例,我们通过仅记录到控制台来对此做出反应:

¥For example, let's create a start event, and as a matter of providing a sample, we react to that by just logging to the console:

eventEmitter.on('start', () => {
  console.log('started');
});

当我们运行时

¥When we run

eventEmitter.emit('start');

触发事件处理程序函数,我们得到控制台日志。

¥the event handler function is triggered, and we get the console log.

你可以将参数作为附加参数传递给 emit(),从而将参数传递给事件处理程序:

¥You can pass arguments to the event handler by passing them as additional arguments to emit():

eventEmitter.on('start', number => {
  console.log(`started ${number}`);
});

eventEmitter.emit('start', 23);

多个参数:

¥Multiple arguments:

eventEmitter.on('start', (start, end) => {
  console.log(`started from ${start} to ${end}`);
});

eventEmitter.emit('start', 1, 100);

EventEmitter 对象还公开了其他几种与事件交互的方法,例如

¥The EventEmitter object also exposes several other methods to interact with events, like

  • once():添加一次性监听器

    ¥once(): add a one-time listener

  • removeListener() / off():从事件中删除事件监听器

    ¥removeListener() / off(): remove an event listener from an event

  • removeAllListeners():删除事件的所有监听器

    ¥removeAllListeners(): remove all listeners for an event

你可以在 官方文档 中阅读有关这些方法的更多信息。

¥You can read more about these methods in the official documentation.