current position:Home>How to create JavaScript custom events

How to create JavaScript custom events

2022-04-29 11:21:06PHP Development Engineer

You must have dealt with a lot of incidents , For example, click events or form submission . Event monitoring is very helpful for many use cases , But sometimes we need to create our own custom events to handle complex interactions . In this passage , I'll tell you about creating custom events , What you need to know about listening to custom events and creating double-click custom events .

How to create custom events

Creating custom events sounds difficult , But you only need the following simple line of code .

const myEvent = new Event("myCustomEvent")

You can create a new one through the event constructor Event object . In the most basic form , You just need to pass a string to the constructor , This string is the event name you defined . In order to monitor this event , You can add this event listener to the element you want to listen to , as follows :

document.addEventListener("myCustomEvent", e => {
  console.log(e)
})

The last step , What you need to do , Trigger the event created and listening .

document.dispatchEvent(myEvent)

That's what we need dispatchEvent Function . Every element has this method , All you have to do is pass the object you created to it .

If we put the above together , We get a basic event , This event is in our document Element trigger , The relevant event content will be printed out .

The most basic form of this event object is shown in the figure . It contains a lot of information , The most important part I highlight here .

isTrusted Property only means that the event is triggered by user interaction , Or by custom JavaScript Code triggered . for example , When the user clicks the button , Event will isTrusted Set to true, And our custom event will set it to false, Because the event was caused by JavaScript The trigger .

target To call dispatchEvent The elements of the function .

type Refers to the name of the event .

Event customization

You may have noticed , There are properties in the details above bubbles, cancelable and composed attribute . These are actually , Options that can be configured when we create custom events .

const myEvent = new Event("myCustomEvent", {
  bubbles: true,
  cancelable: true,
  composed: true
})

Bubbling bubbles

When an event is triggered ,bubbles Property determines whether the event can pass through HTML Bubbling . This value defaults to false, This means that bubbling is not allowed , If you want to call the parent event HTML Elements , You can set it to true.

const bubbleEvent = new Event("bubbleEvent", { bubbles: true })
const defaultEvent = new Event("defaultEvent", { bubbles: false })

document.addEventListener("bubbleEvent", () => {
  // This will get called since the event will bubble up to the document from the button
  console.log("Bubble")
})

document.addEventListener("defaultEvent", () => {
  // This never gets called since the event cannot bubble up to the document from the button
  console.log("Default")
})

const button = document.querySelector("button")
button.dispatchEvent(bubbleEvent)
button.dispatchEvent(defaultEvent)

It can be cancelled cancelable

cancelable Property determines whether an event can be called by e.preventDefault() Cancel . The default is false Can not be . If the attribute is true value , You can call e.preventDefault() Method .e.preventDefault() The event will be defaultPrevented Property is set to true.

const cancelableEvent = new Event("cancelableEvent", { cancelable: true })
const defaultEvent = new Event("defaultEvent", { cancelable: false })

document.addEventListener("cancelableEvent", e => {
  e.preventDefault()
  console.log(e.defaultPrevented) // True
})

document.addEventListener("defaultEvent", e => {
  e.preventDefault()
  console.log(e.defaultPrevented) // False
})

document.dispatchEvent(cancelableEvent)
document.dispatchEvent(defaultEvent)

Combine composed

composed Property determines whether an event can pass through the shadow DOM Spread it up . The default value is false. This attribute is only available when you use custom HTML Elements and shadows DOM Only when , What it does is allow events to be in the shadow DOM Spread outside . If you want to be in the shadow DOM Events triggered in can be in the shadow DOM The alien was caught , Just set it to true.

It doesn't matter if you don't understand , I'll learn later

Pass custom data to events

When you use custom events , Events you want custom data to pass to you . Use new Event Constructor is impossible , That's why there's a second way to create events .

const myEvent = new CustomEvent("myEvent", { detail: { hello: "World" } })

CustomEvent Constructor replaces Event Constructors . This is related to new Event They work the same way , But you can put detail Properties and bubbles,cancelable and composed Property is passed to the second parameter .detail Everything you set in the properties will be passed to the event listener .

const myEvent = new CustomEvent("myEvent", { detail: { hello: "World" } })

document.addEventListener("myEvent", e => {
  console.log(e.detail) // { hello: "World" }
})

document.dispatchEvent(myEvent)

Naming conventions

Before we talk about the example of custom double-click event , I'd like to talk about naming conventions first . You can name custom events whatever you want , But still follow the naming convention , To make it easier to use your own code . The most common naming convention event , Is to add... To the event custom: Prefix .

custom: To distinguish between custom events and their own events , and , If JavaScript Add a new event with the same name as your event , It also ensures that your code doesn't break . for instance , If JavaScript Added a name called doubleclick event , Then you're already at the time doubleclick Custom events , You'll have a problem , Because your custom code will trigger this event , And the browser will try to trigger its own copy .

// Always use some form of naming convention
const myEvent = new Event("custom:doubleClick")

Double-click the event

In this case , We will create a double click event , As long as you click an element in a short time , Will trigger the event . This event also passes the total time between button clicks as custom data .

First , We need to create a normal click event listener to ensure that there is a double click .

const button = document.querySelector("button")

const MAX_DOUBLE_CLICK_TIME = 500
let lastClick = 0
button.addEventListener("click", e => {
  const timeBetweenClicks = e.timeStamp - lastClick
  if (timeBetweenClicks > MAX_DOUBLE_CLICK_TIME) {
    lastClick = e.timeStamp
    return
  }

  // TODO: Double click happened. Trigger custom event.
  lastClick = 0
})

The above code is used timeStamp Property to ensure the time between click events on the button . If the time between clicks exceeds 500 millisecond . Will immediately return and update lastClick Value . Once we're in 500 Two clicks in milliseconds , We will pass if Check and trigger our double click event . So , Create our event and call it .

For our custom events , We set all options to true, Because by default , Click event to set all these properties to true, And we want double clicking to behave like normal clicking . We will also timeBetweenClicks Pass on to detail In the options . Last , We schedule events on the target of the event , Here is the button element . The last thing we have left to do is to monitor events .

We just added a simple event listener to the button , It will print out Double Click Time between .

summary

Custom events are JavaScript A good solution to handle gestures and double-click events in , most important of all , They are very easy to use and implement .

Last

If you think this article is useful to you , Please give our open source project a little bit star:http://github.crmeb.net/u/defu Thank you for  !

copyright notice
author[PHP Development Engineer ],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290953303045.html

Random recommended