Using objects with addEventListener in vanilla Javascript
source link: http://www.js-craft.io/blog/using-objects-with-addeventlistener-in-vanilla-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Using objects with addEventListener in vanilla Javascript
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') );
Coll stuff! Kudos to Stefan Judis for writing about this one .
I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.
Newsletter subscribe:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK