简体   繁体   中英

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?

Some of the answers may be similar, the Question is different . You can see from the comments below the answers there are many solutions that are different because this is about ES6 not old JavaScript. This question is also about event listeners, not callbacks. A such there are other solutions that don't apply to plain callbacks.


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(...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>

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)

 class SomeClass { constructor(msg, elem) { this.msg = msg; elem.addEventListener('click', this._onClickListener.bind(this)); } _onClickListener() { console.log(this.msg); } } var s = new SomeClass("hello", document.querySelector("button"));
 <button>click me</button>

I might not be totally understanding you, but it works with bind .

Basically, bind creates a copy of the bound function with this always set to the specified reference. (You can also bind arguments, but that's irrelevant in this case.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM