📜 ⬆️ ⬇️

Custom javascript events

Translation of the article "JavaScript CustomEvent", David Walsh

Since the advent of JavaScript, events have been the gateway to user interaction in the browser. Events tell us not only that the interaction takes place, but also the type of interaction, the elements involved, and provide methods for working with the event. Creating and triggering custom events has always been more difficult. With the use of the JavaScript CustomEvent API, this complexity can be eliminated. CustomEvent API allows developers not only to create custom events, but also to trigger them on DOM elements, passing data along the chain. Most importantly, the API is as simple as possible!

Javascript

In a custom event there are only two components: the name and the ability to initiate it. Adding an event handler to an item, meanwhile, remains the same:
myElement.addEventListener("userLogin", function(e) { console.info("Event is: ", e); console.info("Custom data is: ", e.detail); }) 

In the code above, we added a userLogin event, as easy as we could add a built-in mouseover or focus event — everything remains the same. What is different is the creation and initiation of an event:
 // First create the event var myEvent = new CustomEvent("userLogin", { detail: { username: "davidwalsh" } }); // Trigger it! myElement.dispatchEvent(myEvent); 

The constructor of the CustomEvent class allows, when creating, to pass the name of the event, as well as your additional properties; The dispatchEvent method dispatchEvent event on the passed item. Let's make this event super customizable by adding the ability to cancel its bubbling:
 var myEvent = new CustomEvent("userLogin", { detail: { username: "davidwalsh" }, bubbles: true, cancelable: false }); 

Creating and initiating custom events with passing custom data is an incredibly useful thing. You can not only come up with your own agreement on the naming of events, but you can also transfer the necessary data to handlers! You can view support for the CustomEvent API on MDN , but still, this API works in most modern browsers.

')

Source: https://habr.com/ru/post/229189/


All Articles