Custom events in JavaScript

A lot of the code we write involves reactions to events. I/O events, such as mouse clicks or keyboard events. Listen for network events when HTTP calls are made.

These are what I call built-in events.

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

On the front end, we use the Event object provided by the browser:

const anEvent = new Event('start');

You can use trigger event

document.dispatchEvent(anEvent)

And trigger the event listener when this happens:

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

you can use itCustomEventBuilt-in objects instead ofEvent, It accepts an object as the second parameter:

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

useCustomEvent, In the event listener, you can useevent.detail(You cannot use other attributes):

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

On the backend, Node provides us with the option to build a similar system with the following options:eventsModule.

In particular, this module providesEventEmitterClass, we will use it to handle events.

You use initialize

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

Among other things, the subject also exposedonwithemitmethod.

  • emitUsed to trigger events
  • onUsed to add a callback function that will be executed when the event is triggered

For example, let's create astartEvent, and provide an example, we can react to this by simply logging in to the console:

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

When we run

eventEmitter.emit('start')

The event handler is triggered and we get the console log.

You can pass parameters to the event handler as additional parameters to pass them to the event handler.emit():

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

eventEmitter.emit(‘start’, 23)

Multiple parameters:

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

eventEmitter.emit(‘start’, 1, 100)

Download mine for freeJavaScript beginner's manual


More js tutorials: