0

I have a custom button using this Custom Element class:

class Button extends HTMLElement {
    connectedCallback() {
        document.addEventListener('click', this.reusableClickHandler)
    }

    disconnectedCallback() {
        document.removeEventListener('click', this.reusableClickHandler)
    }

    reusableClickHandler() {
        console.log(this) // how to get `this` to equal the button instance
    }
}

The custom button listens for clicks on document, and removes the stale event handlers when the button is removed from the DOM.

Is it possible for me to keep this within reusableClickHandler() equal to the button instance? I'm not sure how to write it.

Also I know that a button created this way is not optimal, it's just to demonstrate the problem. Thanks

somebodysomewhere
  • 1,102
  • 1
  • 13
  • 25

1 Answers1

1

To get a specific this reference in callbacks, you can bind the callback with the desired object.

document.addEventListener('click', this.reusableClickHandler.bind(this));

Just a side note, bind returns a new function and if there is a requirement to remove the event listener then you might want to store the bound function in a class variable(maybe in the constructor) and use the class property to add and remove the event listener.

Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • Another pattern is to keep the ``addEventListener`` and ``removeEventListener`` in the same scope: https://stackoverflow.com/questions/54921027/remove-event-listener-that-has-been-added-using-bindthis/54945857#54945857 – Danny '365CSI' Engelman May 06 '20 at 07:51
  • @Danny'365CSI'Engelman Nice way of handling add/remove. – Ashish Ranjan May 06 '20 at 07:55
  • Whenyou have multiple handlers, add an array: ``this.handlers.push(listen(...))`` then in the ``disconnectedCallback`` all you need is: ``this.handlers.forEach(removeFunc=> removeFunc())`` – Danny '365CSI' Engelman May 06 '20 at 07:59