清理自定义元素中的事件侦听器

cleaning up event listeners in custom elements

本文关键字:事件 侦听器 元素 自定义      更新时间:2023-09-26

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
});

detachedCallback()方法中的Event Listeners附加到windowdocument等对象时,您应该删除它们,这些对象将在自定义元素的生命周期之后保留。

但是,如果Event Listener附加到自定义元素本身(或其正确 DOM 中的任何元素),则在其所有者元素被销毁时,它将被删除。也就是说,在上面的示例中,您不必针对this调用removeEventListener()