Ben
Ben

Reputation: 3654

Reason for removing event listener on disconnectedCallback of web component

I saw online a example of removing event listeners of a button in a web components dom in its disconnectedCallback:

class MyComponent extends HTMLElement {
    constructor() {
        this.attachShadow({ mode: "open" });
        this.shadowRoot.innerHTML = "<button>Click</button>";
    }

    myEvent() {
        ...
    }

    connectedCallback() {
        this.shadowRoot.querySelector("button").addEventListener("click", this.myEvent.bind(this));
    }

    // Removes event here:
    disconnectedCallback() {
        this.shadowRoot.querySelector("button").removeEventListener("click", this.myEvent.bind(this));
    }
}

Is there a reason for doing this? As the button is out of dom there wouldn't be issues with it firing? Is there memory leak concerns? It is not listed in the events section of web components best practises. I could understand if was event listener on the window etc but don't understand the effects if the event is triggered by something which is not connected

Upvotes: 5

Views: 2562

Answers (1)

Antal Alin
Antal Alin

Reputation: 166

You can reconnect an element any time and by doing that, you will attach twice an event;

const elem = document.createElement('my-component');

document.body.appendChild(elem);

document.body.removeChild(elem);
document.body.appendChild(elem);

if your event is doing an API call, this will result in a duplicated request

Upvotes: 2

Related Questions