Categories
JavaScript Answers

How to Pass Additional Data via Custom Events in JavaScript?

Spread the love

Sometimes, we want to pass additional data via custom events in JavaScript.

In this article, we’ll look at how to pass additional data via custom events in JavaScript.

Pass Additional Data via Custom Events in JavaScript

To pass additional data via custom events in JavaScript, we can pass an object into the CustomEvent constructor.

For instance, we can write:

window.addEventListener("MyEvent", (evt) => {
  console.log(evt.detail);
});

const evt = new CustomEvent("MyEvent", {
  detail: "Any Object Here"
});
window.dispatchEvent(evt);

to listen to the MyEvent event with the window.addEventListener method.

In the event handler, we log the value of the evt.detail property, which will be set when we pass in an object into the CustomEvent constructor’s 2nd argument with the detail property.

The first argument of the CustomEvent constructor is the event name.

Finally, we call window.dispatchEvent with the evt object to emit the event.

Therefore, we should see 'Any Object Here' logged from the event handler.

Conclusion

To pass additional data via custom events in JavaScript, we can pass an object into the CustomEvent constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *