2016-01-30 140 views
3

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

回答

4

你應該在detachedCallback()方法去除Event Listeners當他們連接到像windowdocument對象,你的自定義元素的生命之後將繼續存在。

但是,如果Event Listener附加到自定義元素本身(或其適當的DOM內的任何元素),它將在其所有者元素被銷燬時被移除。 也就是說,在上面的示例中,您不必撥打removeEventListener()反對this

+0

非常好,這就是我希望聽到的 - 謝謝! – AnC

相關問題