current position:Home>How to create JavaScript custom events
How to create JavaScript custom events
2022-04-29 11:21:06【PHP 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
The sidebar is recommended
- Install and configure nginx in Linux Environment
- Vue dynamically binds attributes and dynamically obtains attribute values
- Summary method of Vue value in key pair mapping
- Vue simply realizes the addition, deletion and modification of each tab page without route jump
- Vue time control common processing
- Vue validation array
- Simple and easy to let you know what AJAX is, even if you are a little white, a rookie can understand it!
- Receive the JSON string from the front end, and summarize the methods of parsing and value taking at the back end
- Solution: httpmessagenotreadableexception: JSON parse error: invalid UTF-8
- Vuetify: install vuetify from scratch
guess what you like
Install CSS from tailwind
Ubuntu 16 wireless network card model query and driver installation, Lenovo g400 bcm43142 network card WiFi
Some color knowledge to understand at the front end
Functional programming of front-end development
A front-end interview question -- implementing an encapsulated Ajax device (promise version)
Dynamic components of angular
Front end written test pit -- JS implicit conversion
Shallow understanding of HTTP
React style modification background invalid
Finding the k-th small element of ordered matrix (dichotomy idea)
Random recommended
- JavaScript functions -- pre parsing, Iife, advanced functions, recursion
- JavaScript object
- How to introduce element plus gracefully in vue3 project on demand
- Component slot Vue js
- How to write game interface style in HTML
- Ask some front-end questions.
- Information | driverless taxi has come to Beijing. Xiaoma Zhixing has been approved to carry out automatic driving service in Beijing
- [taro react] - H5 route configuration cancels # on the route
- Reverse advanced, using ast technology to restore JavaScript obfuscated code
- JavaScript object
- Vue introduces vant / elementul
- JavaScript queue“
- Vue content summary
- vue3. 0
- Small tips: detection of JS font loading failure or completion
- CSS is a box that has been climbing
- Leetcode215 - the kth largest element in the array - quick sort - quick select - template
- CSS adds effect to the four corners of div
- HTTP error 500.19 internal server error occurred in the integration pageoffice of aspnetcore project,
- Front end < TD > what is the word limit of the label
- Construction and development of automatic test platform based on HTTP runner
- Application of RT thread - use RT thread on stm32l051 (v. conclusion of wireless temperature and humidity sensor)
- Expose Dubbo to HTTP service
- Put the front end into the spring cloud project
- Front end learning day 4 - CSS
- Vue URL jump page with parameters
- JavaScript Chapter 13 traversal of arrays and implicit parameters of function methods
- These CSS efficiency improvement skills, you need to know!
- Beijing has opened the pilot of unmanned operation of passenger cars, and the driverless air outlet has arrived
- Test theory series - Test Case elements and design methods Part II
- How to make the peak value of measured output voltage not less than 2V
- Hexo quickly set up its own blog
- Gee synthetic cloudless landsat-8 and sentry-2 data
- Prototype object creation method case JavaScript specific implementation steps
- YAF CLI and HTTP access modes
- Simple HTML + CSS animation web page production DW simple animation web page production
- The correct way for web programmers to make a pink girl series happy birthday blessing web page (HTML + CSS + JS)
- HTML + CSS + JS to make simple animation web pages
- HTML gourmet web page production DW static web page production div + CSS gourmet web page implementation and production
- Programmer 520 Tanabata Valentine's Day confession code HTML + JS + CSS petal photo album web page template programmer confession necessary