跳到内容

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  = ('node:events');

const  = new ();

这个对象暴露了包括 onemit 方法在内的许多方法。

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

  • emit 用于触发一个事件
  • on 用于添加一个回调函数,当事件被触发时将执行该函数

例如,让我们创建一个 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', () => {
  .('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',  => {
  .(`started ${}`);
});

eventEmitter.emit('start', 23);

多个参数:

🌐 Multiple arguments:

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

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

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

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

  • once(): 添加一次性监听器
  • removeListener() / off():从事件中移除事件监听器
  • removeAllListeners(): 移除某个事件的所有监听器

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

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