'Should I add event listeners in component class?
I'm using Vanilla JavaScript Modules. I have main.js file (where I start the app) and other component files (hamburger.js, modal.js etc.) These components have elements I want to listen but I don't know if I should add their event listeners in their own class or I should add them in main js.
Event Listeners in Class Example
export default class Hamburger {
constructor(element) {
this.element = element;
}
handleClick() {
// code...
}
addEventListeners() {
this.element.addEventListener('click', this.handleClick);
}
}
Event Listeners in Main JavaScript File Example
import Hamburger from './hamburger.js';
const element = document.querySelector('.js-element');
const hamburger = new Hamburger(element);
hamburger.element.addEventListener('click', handleClick);
These are the examples that come to my mind. If there's a better way without using any framework or library, I'm open to it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
