Lost reference to this in LWC with addEventListener
You have to remember that the this
value changes depending on how the function is invoked. Use bind
to bind the this
value to the function and don't forget to remove the listener since you are adding it globally:
connectedCallback() {
// Save a reference to the bound function since it has a different identity
this._listenForMessage = this.listenForMessage.bind(this);
window.addEventListener('message', this._listenForMessage);
}
disconnectedCallback() {
window.removeEventListener('message', this._listenForMessage);
}
I solved it by changing:
window.addEventListener("message", this.listenForMessage);
to
window.addEventListener("message", this.listenForMessage.bind(this));
I believe that is the correct way to do it.