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