I was wondering, what is the purpose of CustomEvent
, because it can be easily emulated by good old Event
.
So, what is the difference between:
var e = new Event("reload"); e.detail = { username: "name" }; element.dispatchEvent(e);
and
var e = new CustomEvent("reload", { detail: { username: "name" } }); inner.dispatchEvent(e);
Why does CustomEvent
exist if it is easy to attach custom data to ordinary Event object?
The CustomEvent interface represents events initialized by an application for any purpose. Note: This feature is available in Web Workers.
dispatchEvent is what you call if you want to send or trigger an event. Internally, the browser is doing this whenever the user rotates their device, which triggers orientationchange . In this specific example, you don't need to trigger this manually unless you need to do so for testing.
A custom event can be created using the CustomEvent constructor: const myEvent = new CustomEvent("myevent", { detail: {}, bubbles: true, cancelable: true, composed: false, }); As shown above, creating a custom event via the CustomEvent constructor is similar to creating one using the Event constructor.
It's not the same. You can't set the detail
of a real CustomEvent:
var event = new CustomEvent('myevent', {detail:123}); event.detail = 456; // Ignored in sloppy mode, throws in strict mode console.log(event.detail); // 123 var event = new Event('myevent'); event.detail = 123; // It's not readonly event.detail = 456; console.log(event.detail); // 456
Yes, you could use Object.defineProperty
. But I guess the point is that the argument of CustomEvent
was supposed to set some internal data of the event. Now it only considers detail
, which is not used internally. But a future spec could add something new, and then you may not be able to set that internal data by using properties.
A CustomEvent also inherits from CustomElement.prototype
. That only adds detail
and the deprecated initCustomEvent
. But you can add your own methods or properties in there, which won't be inherited by other events. But I don't recommend this, you shouldn't modify objects you don't own.
So basically you can use CustomEvent
in order to classify the event differently than other events. See this graphic from an old spec
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With