Recently, I discovered that the listener passed to addEventListener
can actually be an object with a handleEvent
function instead of just a callback function (here).
However, I encountered an issue when trying to use handleEvent
as a class method:
class Foo {
static handleEvent() {
console.log(`clicked`);
}
}
document.body.addEventListener(`click`, Foo);
This resulted in the error message:
Uncaught TypeError: Class constructor Foo cannot be invoked without 'new'
To bypass this, I could simply pass in Foo.handleEvent
instead. But out of curiosity and for educational purposes, I'm wondering why static handleEvent
doesn't work?