disconnect
Disconnect a StacheElement
instance from the DOM.
disconnect()
Calling disconnect
will clean up an element's event handlers and call its disconnected hook. Normally this is called by the disconnectedCallback, but can be called manually for testing:
import { StacheElement } from "can/everything";
const logs = [];
class MyElement extends StacheElement {
static view = `
<p>{{this.name}} has been running for {{this.time}} seconds</p>
`;
static props = {
name: { type: String, default: "App" },
time: { type: Number, default: 0 }
};
connected() {
this.listenTo("name", (ev, newName) => {
logs.push(`name change to ${newName}`);
});
let intervalId = setInterval(() => {
this.time++;
}, 1000);
return () => {
clearInterval(intervalId);
};
}
disconnected() {
logs.push("disconnected");
}
}
customElements.define("my-el", MyElement);
const myEl = new MyElement()
.connect();
myEl.innerHTML; // -> <p>App has been running for 0 seconds</p>
myEl.name = "Counter";
logs; // -> [ "name changed to Counter" ]
myEl.innerHTML; // -> <p>Counter has been running for 0 seconds</p>
// ...some time passes
myEl.innerHTML; // -> <p>Counter has been running for 3 seconds</p>
myEl.disconnect();
myEl.innerHTML; // -> <p>Counter has been running for 3 seconds</p>
myEl.name = "Stopped Counter";
logs; // -> [ "name changed to Counter", "disconnected" ]
// ...some time passes
myEl.innerHTML; // -> <p>Stopped Counter has been running for 3 seconds</p>
Returns
{Element}
:
The element
instance.
Purpose
For testing purposes or integration with other libraries, disconnect
can be called to simulate an element being disconnected from the DOM.
The first time disconnect
is called, it will:
- call stopListening.
- call a teardown handler returned by the connected hook.
- call the disconnected hook.
Subsequent calls to disconnect
will not have any effect.