Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event vs CustomEvent

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?

like image 831
Sergey Alaev Avatar asked Nov 24 '16 21:11

Sergey Alaev


People also ask

What is CustomEvent?

The CustomEvent interface represents events initialized by an application for any purpose. Note: This feature is available in Web Workers.

What is a dispatch event?

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.

How do I use CustomEvent in Javascript?

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.


1 Answers

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

like image 133
Oriol Avatar answered Sep 19 '22 12:09

Oriol