Is there a way to create a custom class that extends the EventTarget DOM API class?
Let's say we have the following class:
class MyClass extends EventTarget {
constructor() {
super();
}
private triggerEvent() {
this.dispatchEvent(new Event('someEvent'));
}
}
However, upon instantiation, an error is encountered:
ERROR TypeError: Failed to construct 'EventTarget': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
This issue seems to stem from the requirement of proper ES2015 classes for this API to function, whereas code transpilation is done at the ES5 level.
If attempting to use the following constructor instead:
constructor() {
Reflect.construct(EventTarget, [], MyClass);
}
A new error arises when trying to invoke addEventListener()
:
.ERROR TypeError: Illegal invocation
In addition, a TypeScript compilation error occurs:
.error TS2377: Constructors for derived classes must contain a 'super' call.