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

cleaning up event listeners in custom elements

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()