在 attachedCallback
中注册事件监听器时,我是否有责任确保在 detachedCallback
中再次删除它们?
如下面的最小示例所示,该模式相当可预测,所以我想知道浏览器是否已经处理了这个问题?
<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
});
最佳答案
你应该删除 Event Listeners
在detachedCallback()
当它们附加到像 window
这样的对象时的方法或 document
,这将在您的自定义元素生命周期结束后继续存在。
但是如果Event Listener
附加到自定义元素本身(或附加到其适当的 DOM 内的任何元素),它将在其所有者元素被销毁时被删除。
也就是说,在上面的示例中,您不必调用 removeEventListener()
反对this
.
关于javascript - 清理自定义元素中的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35100584/