gman gman - 1 month ago 5
Javascript Question

Is there a ES6 shortcut for using member functions as event listeners?

This is not a duplicate of How to access the correct `this` / context inside a callback?

The answer may be similar, the Question is different. You can see from the answers below that many of the answers are very different because this is about ES6 not old JavaScript




If I have a class and I want to have some event call a function in that class I end up having to writing a bunch of boilerplate

class SomeClass {
constructor(msg, elem) {
this.msg = msg;
elem.addEventListerer('click', (...args) => { // Can these
this._onClickListener.apply(this, ...args); // three lines
}); // be simpler?
}
_onClickListener() {
console.log(this.msg);
}
}


Is there some ES6 syntactic sugar for using class methods as listeners? Ideally I'd like be able to do something like

class SomeClass {
constructor(msg, elem) {
this.msg = msg;
elem.addEventListener('click', this._onClickListener);
}
_onClickListener() {
console.log(this.msg);
}
}


And have it correctly set
this
and pass all arguments regardless of the event.

But that doesn't work. Without the boilerplate
this
is not set.



class SomeClass {
constructor(msg, elem) {
this.msg = msg;
elem.addEventListener('click', this._onClickListener);
}
_onClickListener() {
console.log(this.msg); // this is wrong
}
}

var s = new SomeClass("hello", document.querySelector("button"));

<button>click me</button>




Answer

You have to bind the context:

class SomeClass {
  constructor(msg, elem) {
    this.msg = msg;
    this._onClickListener = this._onClickListener.bind(this);
    elem.addEventListener('click', this._onClickListener);
  }
  _onClickListener() {
     console.log(this.msg);
  }
}

Additional advantage of this solution is that you can remove listener elem.removeEventListener(this._onClickListener)

Comments