Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

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 šŸ‘.

Home Screencasts Best of Newsletter Search X