The default way we use addEventListener
is in conjunction with a callback function:
document.querySelector('.alert-me')
.addEventListener('click', () => alert('This is an alert !!!');
However, it seems we can also pass it objects, as long as they have defined the handleEvent()
method:
class MyHandlerObj {
constructor() {
this.alerts = 0;
}
// we need to have this method as it is
// defined in the `EventListener` interface
handleEvent() {
this.alerts++;
alert('Alerts triggered ' + alerts);
}
}
document.querySelector('.alert-me')
.addEventListener('click', new MyHandlerObj());
And, based on this, we can build a parent like :
class MyComponent {
constructor (el) {
this.el = el
this.el.addEventListener('click', this)
}
handleEvent (event) {
console.log('my component element was clicked')
}
destroy () {
this.el.removeEventListener('click', this)
}
}
const component = new MyComponent(document.querySelector('button') );
You can use this also when adding event listeners to mutiple elements in Javascript.
Coll stuff! Kudos to Stefan Judis for writing about this one 👏.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.