I have parent class which is gets all children class methods and adds corresponding eventListener to the element.
class ElementEventController {
attachEventsToElement(element, methodNames) {
for (const methodName of methodNames) {
const method = this[methodName];
if (typeof method === "function") {
element.addEventListener(methodName, method.bind(this));
}
}
}
}
and for example if i create a SettingsIcon class which represents an html dom element and create corresponding event such as click, mouseleave, mouseover... so on.Controller class will add corresponding event to the element.
class SettingsIcon extends ElementEventController {
constructor(element) {
super();
this.attachEventsToElement(element, SettingsIcon.getMethodNames());
}
static getMethodNames() {
return Object.getOwnPropertyNames(SettingsIcon.prototype)
.filter(name => name !== "constructor");
}
click() {
console.log("SettingsIcon's click method executed");
}
mousemove(){
console.log('mouse is moving on the element')
}
}
const t = new SettingsIcon(document.getElementById("settings-icon"));
Right now this works as expected but the problem is as you can every time child class should have some methods and this is annoying and repeating process how to simplify this process?
