This question is unique and not a repetition of the query posed in How to access the correct `this` context inside a callback?
Although some answers may overlap, the Question at hand differs. The comments below the answers indicate varied solutions, particularly as this discussion pertains to ES6 rather than traditional JavaScript. Furthermore, it specifically addresses event listeners, not just callbacks, which leads to alternative approaches beyond basic callback functions.
In instances where a function within a class needs to be invoked by an event, there tends to be a significant amount of redundant code that needs to be written
class SomeClass {
constructor(msg, elem) {
this.msg = msg;
elem.addEventListerer('click', (...args) => {
this._onClickListener(...args);
});
}
_onClickListener() {
console.log(this.msg);
}
}
Is there a more concise syntax in ES6 for using class methods as event listeners? Ideally, I would prefer to achieve something like
class SomeClass {
constructor(msg, elem) {
this.msg = msg;
elem.addEventListener('click', this._onClickListener);
}
_onClickListener() {
console.log(this.msg);
}
}
However, this approach does not function as intended. Without the additional code, the proper assignment of this
does not occur.
class SomeClass {
constructor(msg, elem) {
this.msg = msg;
elem.addEventListener('click', this._onClickListener);
}
_onClickListener() {
console.log(this.message);
}
}
var s = new SomeClass("hello", document.querySelector("button"));
<button>click me</button>