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
});
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
});
Share
Improve this question
edited May 16, 2016 at 22:28
Supersharp
31.2k11 gold badges101 silver badges147 bronze badges
asked Jan 30, 2016 at 10:23
AnCAnC
4,20110 gold badges47 silver badges70 bronze badges
1 Answer
Reset to default 22You 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
.