Search code examples
javascriptclosurescustom-element

Custom Element class with a reusable event handler method


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


Solution

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