I'm writing a web component enhancer function and I need to run something when the element is removed from the DOM - but I know this after the fact. I've used MutationObserver - but my component is used a lot around the page and multiple mutation observers are causing a performance issue.
Here's an attempt to do this without MutationObserver:
class TestComponent extends HTMLElement {
disconnectedCallback() {
console.log('CB');
}
}
window.customElements.define('test-component', TestComponent);
function enrichComponent(component) {
const originalDisconnectedCallback = component.disconnectedCallback;
component.disconnectedCallback = function() {
originalDisconnectedCallback();
console.log('CB1');
}
}
const component = document.createElement('test-component');
enhancer(component);
document.body.appendChild(component);
component.remove(); // logs 'CB' but no 'CB1'
This doesn't work.
Is there a way to 'monkeypatch' disconnectedCallback?