current position:Home>How to create JavaScript custom events
How to create JavaScript custom events
2022-04-29 16:58:10【Xianling Pavilion】
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")
Copy code
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)
})
Copy code
The last step , What you need to do , Trigger the event created and listening .
document.dispatchEvent(myEvent)
Copy code
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
})
Copy code
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)
Copy code
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)
Copy code
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" } })
Copy code
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)
Copy code
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")
Copy code
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
})
Copy code
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 !
Get the source code address for free :http://ym.baisouvip.cn/html/wzym/36.html
PHP Learning manual :https://doc.crmeb.com
Technical exchange forum :https://q.crmeb.com
copyright notice
author[Xianling Pavilion],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291456022757.html
The sidebar is recommended
- Function of host parameter in http
- Use nginx proxy node red under centos7 and realize password access
- Centos7 nginx reverse proxy TCP port
- In eclipse, an error is reported when referencing layuijs and CSS
- Front end online teacher Pink
- Learn to use PHP to insert elements at the specified position and key of the array
- Learn how to use HTML and CSS styles to overlay two pictures on another picture to achieve the effect of scanning QR code by wechat
- Learn how to use CSS to vertically center the content in Div
- Learn how to use CSS to circle numbers
- Learn to open and display PDF files in HTML web pages
guess what you like
The PHP array random sorting function shuffle() randomly scrambles the order of array elements
JQuery implements the keyboard enter search function
16 ArcGIS API for JavaScript 4.18 a new development method based on ES modules @ ArcGIS / core
17 ArcGIS API for JavaScript 4.18 draw points, lines and faces with the mouse
18 ArcGIS API for JavaScript 4.18 obtain the length and area after drawing line segments and surface features
Vue environment construction -- scaffold
Build a demo with Vue scaffold
Using vuex in Vue projects
Use Vue router in Vue project
26 [react basics-5] react hook
Random recommended
- 07 Chrome browser captures hover element style
- WebGIS development training (ArcGIS API for JavaScript)
- Solution to the blank page of the project created by create react app after packaging
- 19. Html2canvas implements ArcGIS API for JavaScript 4 X screenshot function
- Introduction to JavaScript API for ArcGIS 13
- Development of ArcGIS API for JavaScript under mainstream front-end framework
- Nginx learning notes
- Less learning notes tutorial
- Vue2 cannot get the value in props in the data of the child component, or it is always the default value (the value of the parent component comes from asynchrony)
- LeetCode 217. Determine whether there are duplicate elements in the array
- I'll write a website collection station myself. Do you think it's ok? [HTML + CSS + JS] Tan Zi
- Front end browser debugging tips
- Application of anti chattering and throttling in JavaScript
- How to create JavaScript custom events
- Several ways of hiding elements in CSS
- node. Js-3 step out the use of a server and express package
- CSS matrix function
- Fastapi series - synchronous and asynchronous mutual conversion processing practice
- How to extend the functionality of Axios without interceptors
- Read pseudo classes and pseudo elements
- About node JS server related concepts
- Access control module (2)
- About virtual lists
- Developing figma plug-in using Vue 3 + vite
- Learn more about the garbage collection engine of chrome V8 JavaScript engine
- Vue3 uses vite instead of webpack
- How to upload applet code through node? Just take a look
- Using H5 video tag in Vue to play local video in pop-up window
- What is the difference between classes in Es5 and ES6?
- [Vue] play with the slot
- [Part 4 of front-end deployment] using docker to build cache and multi-stage construction to optimize single page applications
- Vue2 simple use of vant (based on Vue CLI)
- node. JS server
- React uses concurrent mode. When the rendering phase exceeds the time slice, high priority tasks jump the queue. How will the lanes on the fiber of the previous task be solved
- Vuecli2 multi page, how to remove HTML suffix
- Vue router dynamically modifies routing parameters
- How to use webpack or configure quasar after context isolation is turned on by electron?
- Vue3 how do parent components call child component methods
- Es learning notes (I): http request
- 【Java WEB】AJAX