I wish to create a class which extends EventTarget
, allowing addEventListener()
and dispatchEvent()
to be invoked on it.
Logically, my class wants to be a singleton; if a page accidentally instantiated more than one, its functionality would break. For this reason, I've implemented the entirety of this class's logic as static fields and methods.
Unfortunately extends
doesn’t seem to mesh neatly with static
, so this doesn’t work:
class MyClass extends EventTarget {
static dispatch(type) { MyClass.dispatchEvent(new Event(type)); }
}
MyClass.dispatch('hello');
Uncaught TypeError: MyClass.dispatchEvent is not a function
I also tried:
class MyClass extends EventTarget {
static dispatch(type) { MyClass.prototype.dispatchEvent(new Event(type)); }
}
MyClass.dispatch('hello');
Uncaught TypeError: 'dispatchEvent' called on an object that does not implement interface EventTarget.
There must be something I can do with constructors and prototypes to bring EventTarget
's methods directly into MyClass
. Could someone enlighten me as to how I need to think through this? (Aside from the awkward hack of declaring a class static variable containing an EventTarget, and forwarding things to/from this.)
EventTarget.dispatchEvent()
instead? You're not overriding the method, so there's no need to refer to your own class.dispatchEvent()
needs to knowthis
, which isn't available in a static method.this
in an EventTarget is supposed to be the DOM element that the event is dispatched on. It shouldn't be the class itself.