Two classes listening to one Event. When ClassA gets the event it removes ClassB from DOM and adds it right after it again. The event handlers of ClassB get added and removed by the (dis)connectedCallback functions.
ClassB still notices the Event right after it as well but it does not execute the callback function anymore.
I checked the eventhandler of ClassB. It catches the event and it has a reference to its callback function but it is not executing it. When I disable the method removeAdd()
of ClassA it works.
class ClassA {
constructor() {
window.addEventListener('TEST', this.removeAdd);
}
removeAdd() {
document.body.removeChild(testclass);
document.body.appendChild(testclass);
}
}
new ClassA();
class ClassB extends HTMLElement {
constructor() {
super();
console.log("constructed");
var shadow = this.attachShadow({mode:'open'});
shadow.appendChild(document.createElement('TEXTAREA'));
this.testEL = () => { this.test(); };
}
connectedCallback() {
console.log("connected");
window.addEventListener('TEST', () => { console.log('TEST heared', this.testEL.toString()); });
window.addEventListener('TEST', this.testEL);
}
disconnectedCallback() {
console.log("disconnected");
window.removeEventListener('TEST', this.testEL);
}
test() {
console.log('callback', this);
}
}
customElements.define('test-class', ClassB);
var testclass = new ClassB();
document.body.appendChild(testclass);
function fevent() {
var ev = new Event('TEST');
window.dispatchEvent(ev);
}
fevent();
This is the output when the method removeAdd()
of ClassA is commented out:
constructed
connected
TEST heared () => { this.test(); }
callback <test-class>
This is the output with full code:
constructed
connected
disconnected
connected
TEST heared () => { this.test(); }
But it is not executing this.testEL
. Why?
/edit: After further investigations I noticed that the complete event handler broke after getting removed and added again as even additional new 'TEST' events do not fire the callback function, although the console.log shows that the reference is still there.