Reputation: 3962
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?
Upvotes: 69
Views: 19031
Reputation: 287950
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
Upvotes: 62