Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cleaning up event listeners in custom elements

When registering event listeners in attachedCallback, is it my responsibility to ensure that these are removed again in detachedCallback?

As illustrated in the minimal sample below, the pattern is rather predictable so I'm wondering whether perhaps the browser already takes care of this?

<my-element>0</my-element>
class MyElement extends HTMLElement {
    createdCallback() {
        this.update = this.update.bind(this);
    }

    attachedCallback() {
        this.addEventListener("click", this.update);
    }

    detachedCallback() {
        this.removeEventListener("click", this.update);
    }

    update() {
        this.textContent = Math.random();
    }
}

document.registerElement("my-element", {
    prototype: MyElement.prototype
});
like image 970
AnC Avatar asked Jan 30 '16 10:01

AnC


1 Answers

You should remove Event Listeners in the detachedCallback() method when they are attached to objects like window or document, that will persist after the life of your Custom Element.

But if the Event Listener is attached to the Custom Element itself (or to any element inside its proper DOM), it will be removed at the moment its owner element is destroyed. That is, in your example above, you wouldn't have to call removeEventListener() against this.

like image 81
Supersharp Avatar answered Sep 21 '22 01:09

Supersharp