Back to Lit

01

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

latest947 B
Original Source

First, add the scaffolding for a basic custom directive. Make a class that extends Directive, and then export a directive function created by passing the class to the directive factory. The exported function is what users will call from their template.

ts
import {directive, Directive} from 'lit/directive.js';

class TimeAgoDirective extends Directive {
}

export const timeAgo = directive(TimeAgoDirective);

Next, every directive must implement a render method. Add one to your class that accepts a time argument as a Date object. For now, make a simple version that just returns a string version of the time. We'll make this fancier in a later step.

{% switchable-sample %}

ts
  render(time: Date) {
    return time.toDateString();
  }
js
  render(time) {
    return time.toDateString();
  }

{% endswitchable-sample %}

You won't see anything output yet, because we haven't rendered the directive anywhere.