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
});
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With