0

i have JS class that has method like this:

  setupComponent() {
    document.getElementById("message-input").addEventListener("keydown", this._onKeyPress);
    document.getElementById("send-button").addEventListener("click", this._onSend);
  }

Right under it, there are two methods:

  _onKeyPress(event) {
    if (event.code === "Enter") {
      this._onSend();
    }
  }

  _onSend() {  
     console.log("send");
  }

My question is: why direct call from "click" eventListener works (it logs message), and this._onSend() method, called in _onKeyPress returns this._onSend is not a function.

Also using this._onSend() inside setupComponent() works.

Is this some kind of magic associated with eventListeners?

Macjej
  • 117
  • 1
  • 10
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – dfsq Mar 20 '18 at 18:52
  • The magic is that "this" doesn't always mean what you think it means. – bhspencer Mar 20 '18 at 18:53
  • I thought this might be a problem, but why does it work here then: https://stackoverflow.com/questions/43642729/calling-a-method-from-another-method-in-the-same-class It looks very similar. EDIT: also here: https://stackoverflow.com/questions/35785860/es6-call-class-methods-from-within-same-class/36248405 – Macjej Mar 20 '18 at 18:55

1 Answers1

1

When a function is used as an event handler, its this is set to the element the event fired from this - JavaScript | MDN. So you cant expect your methods to be there, but you can bind your this to your function using Function.prototype.bind().

document.getElementById("message-input")
      .addEventListener("keydown", this._onKeyPress.bind(this));
Hai Alaluf
  • 757
  • 7
  • 15