packages/lit-dev-content/site/tutorials/content/async-directive/08.md
In this step, take a moment to confirm the disconnect() and reconnect()
lifecycle are working as expected.
Add some code to the example element that removes the host element from the DOM
for a second, then puts it back in. In the time-ago-example element's
template, add the @click event listener to the <p>:
return html`
<p @click=${this.handleClick}>
This page was rendered ${timeAgo(timeCreated)}.
</p>
`;
And then add this method to the class. As you see, the host element will be removed, and then a second later it will be re-inserted into the DOM:
{% switchable-sample %}
handleClick() {
const parent = this.parentNode;
this.remove();
setTimeout(() => parent!.appendChild(this), 1000);
}
handleClick() {
const parent = this.parentNode;
this.remove();
setTimeout(() => parent.appendChild(this), 1000);
}
{% endswitchable-sample %}
Next, in our time-ago directive class, add some log statements to
ensureTimerStarted and ensureTimerStopped:
ensureTimerStarted() {
console.log('timer started');
...
}
ensureTimerStopped() {
console.log('timer stopped');
...
}
If you open devtools, you should see a log statement after the initial render:
timer started
When you click on the text rendered in the sample element, the element will be disconnected for a second, and then reconnected. You should see two more log statements, one for the disconnection, another for the reconnection:
timer stopped
timer started
If you comment out the last line of handleClick that reconnects the element
and click on the text, you should see the log statements indicate the timer
stopped and did not restart -- confirming the directive will be properly cleaned
up if the element it was rendered into is discarded.