Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I successfully add event listeners to DOM elements from within a class?

I have a class in an npm package that is meant to act as a timer and latch onto some other elements for the page it is imported to.

class Timer {
    constructor({seconds, buttonSelector}) {
        this.seconds = seconds;
        this.buttonSelector = buttonSelector;

        this._addEventListeners();
    }

    _addEventListeners = () => {
        document.querySelector(this.buttonSelector).addEventListener.bind(this, 'click', function() {
            console.log(this.seconds);
        });
    }
}

But when I instantiate this class, it seems the event listener does not attach to the button, with no console messages shown. I’m able to verify as such because the getEventListeners() function shows nothing and the behavior does not actually happen.

Is there something I’m missing? I suspect maybe I’m not using bind() correctly, but the lack of error messages is confusing me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

No need to call .bind at all, just use

document.querySelector(this.buttonSelector).addEventListener('click', function() {
  console.log('Test');
});

You only have to use .bind if you want to fix the context in which a function is executed to a specific one. If you want to access the class’ instance via this when the handler is running, either use an arrow function:

.addEventListener('click', () => {
  console.log('Test', this); // <-- That "this" points to the instance
}); 

or bind the handler function:

.addEventListener('click', (function () {
  console.log('Test', this); // <-- That "this" also points to the instance
}).bind(this));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading