I'm defining a custom element
customElements.define("my-button", class extends HTMLButtonElement {
onclick() {
console.log("bar");
}
}, { extends: "button" })
https://jsfiddle.net/tuxkjp3q/
But when I click it nothing happens.
Why is that and how can I attach event handlers to each instance of the class without overriding the constructor?
Edit:
When I inspect the DOM object there is an onclick handler, but it's not functioning. This is confusing
Edit 2:
Further findings, when omitted from the prototype, defining a handler works
customElements.define("my-button", class extends HTMLButtonElement {
constructor() {
super();
this.onclick = () => console.log("bar");
}
}, { extends: "button" })
But when the prototype contains onclick
, the same handler no longer functions
customElements.define("my-button", class extends HTMLButtonElement {
onclick() {
console.log("bar");
}
constructor() {
super();
this.onclick = () => console.log("bar");
}
}, { extends: "button" })
I would be really happy if we can get an explanation of this phenomenon.
EDIT 3:
I've come up with a work around, if anyone faces the same problem. It's probably worth noting that only handlers defined in the direct prototype of the instantiated class will get attached, which is good for performance but probably flawed logic. Anyhow it could be tuned to your requirements.
// Only in the base class
constructor() {
super();
for (let prop of Object.getOwnPropertyNames(this.constructor.prototype)) {
if (prop.indexOf("on") === 0) {
this.addEventListener(prop.substring(2).toLowerCase(), this.constructor.prototype[prop]);
}
}
}
I am still very interested in learning the reason for this.
The problem is you need to define the listener of click... not the function onClick
html