Back to Lit

04

packages/lit-dev-content/site/tutorials/content/async-directive/04.md

latest1.1 KB
Original Source

Instead of extending the basic Directive class, import and extend AsyncDirective.

ts
import {directive, AsyncDirective} from 'lit/async-directive.js';

class TimeAgoDirective extends AsyncDirective {

The AsyncDirective base class adds a few new methods useful for directives that need to do asynchronous rendering:

  • setValue() - Can be called from an async task or event callback outside of the template's update cycle, in order to render a new value asynchronously.
  • disconnected() - Async directives typically need to subscribe to some sort of asynchronous source (awaiting a promise, registering a callback, listening to a DOM event, etc.). This callback allows the directive to unsubscribe and perform any clean up work if its DOM was removed. Without this, directives could leak memory.
  • reconnected() - Like disconnected(), it is also possible that a directive that was removed is subsequently re-connected to the DOM. Thus, async directives should always implement a reconnected callback to become operational again after having been disconnected.

We will make use of these methods later in the tutorial.