最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - cleaning up event listeners in custom elements - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 22

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.

发布评论

评论列表(0)

  1. 暂无评论