I am trying to write an ES6 class for an interactive calendar on my current project.
The Class looks similar to the below:
class Calendar {
constructor (s) {
this.eventButtons = s.eventButtons;
this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
this.eventBoxes = s.eventBoxes;
method1 (e) {
e.preventDefault();
this.method2(e.target.href);
}
method2 (url) {
console.log(url);
}
}
export default Calendar;
I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:
this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);
But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.
Any ideas? I'm hoping this is quite a common issue?