Introduction
This tutorial will take a look at creating custom async directives, which are a powerful feature in Lit for building template helpers.
Standard directives are stateful template helpers that can access the underlying DOM associated with their position in the template. Async directives expand the directive API and lifecycle, allowing the directive to update its rendered result asynchronously and cleanup any subscriptions when the directive is no longer in use.
What you'll learn
- How to make a basic
Directive
- The additional directive API added by
AsyncDirective
- How to update a directive's value asynchronously using
setValue
- How to perform cleanup work in the
disconnected()
callback - Why implementing the
reconnected()
callback is also important
What you'll build
You will make a timeAgo(date)
directive that accepts a JavaScript Date
, and renders human-readable string showing the time that has passed. The directive will re-render its value periodically, so that the string always reflects the time that has passed. We'll be able to then use the directive in a variety of scenarios.
Previous knowledge
We'll assume you have a basic understanding of directives in Lit. Familiarize yourself with directive concepts before starting if needed.