欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript中的自定义事件

程序员文章站 2022-04-04 08:04:52
...

Many of the code we write involves reacting to events. I/O events like mouse clicks or keyboard events. Network events, when you listen to an HTTP call.

我们编写的许多代码都涉及对事件的React。 I / O事件,例如鼠标单击或键盘事件。 侦听HTTP调用时的网络事件。

Those are what I call built-in events.

这些就是我所说的内置事件。

In JavaScript we can create custom events, and the way it works changes in the browser and in Node.js.

在JavaScript中,我们可以创建自定义事件,并且它的工作方式会在浏览器和Node.js中发生变化。

In the frontend we use the Event object which is provided by the browser:

在前端,我们使用浏览器提供的Event对象:

const anEvent = new Event('start');

You can trigger the event using

您可以使用触发事件

document.dispatchEvent(anEvent)

and when this happens, the event listener is triggered:

并在发生这种情况时触发事件侦听器:

document.addEventListener('start', event => {   
  console.log('started!')
})

You can send custom data using the CustomEvent built-in object instead of Event, which accepts an object as the second parameter:

您可以使用CustomEvent内置对象而不是Event来发送自定义数据, Event接受一个对象作为第二个参数:

const anotherEvent = new CustomEvent('start', {
  detail: {
    color: 'white'
  }
})

Using CustomEvent, in the event listener you can ask the data to the event object using event.detail (you can’t use another property):

使用CustomEvent ,可以在事件侦听器中使用event.detail将数据询问给事件对象(不能使用其他属性):

document.addEventListener('start', event => {   
  console.log('started!')
  console.log(event.detail)
})

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

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

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

特别是,此模块提供EventEmitter类,我们将使用该类来处理事件。

You initialize that using

您使用初始化

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

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

该对象展示了onemit方法。

  • emit is used to trigger an event

    emit用于触发事件

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

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

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:

例如,让我们创建一个start事件,并提供一个示例,我们只需登录控制台即可对此做出React:

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

When we run

当我们跑步

eventEmitter.emit('start')

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

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

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

你可以将它们作为额外的参数传递参数给事件处理程序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)



翻译自: https://flaviocopes.com/javascript-custom-events/