I would like to create a custom event emitter in my client-side programs. I am referencing this (sparse) documentation for EventTarget
My implementation attempt
var Emitter = function Emitter() {
EventTarget.call(this);
};
Emitter.prototype = Object.create(EventTarget.prototype, {
constructor: {
value: Emitter
}
});
My desired usage
var e = new Emitter();
e.addEventListener("hello", function() {
console.log("hello there!");
});
e.dispatchEvent(new Event("hello"));
// "hello there!"
Where it fails
var e = new Emitter();
// TypeError: Illegal constructor
What am I doing wrong?
Update
The following is possible, but it's a hack that depends on a dummy DOMElement
var fake = document.createElement("phony");
fake.addEventListener("hello", function() { console.log("hello there!"); });
fake.dispatchEvent(new Event("hello"));
// "hello there!"
I'd like to know how to do this without having to use the dummy element
Emitter.prototype = Object.create(Emitter.prototype, …)
- wait, what? – Bergi Mar 5 '14 at 2:00EventTarget
is just an interface, not a constructor. Also, you cannot inherit from native DOM structures. – Bergi Mar 5 '14 at 2:02Object.create
line sets up the prototype and the proper constructor. It was an attempt to inherit from the EventTarget "class". – naomik Mar 5 '14 at 2:08EventTarget
, but fromEmitter
itself… – Bergi Mar 5 '14 at 2:12