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') );

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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X