Back to Lit

09

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

latest2.1 KB
Original Source

The directive is now complete. Now let's see how and where we could use it.

In our example element template, we've been rendering the timeAgo directive into a child expression as a string:

ts
      <p>This page was rendered ${timeAgo(timeCreated)}.</p>

However, our directive can be used in any expression type, including attribute expressions and property expressions. So let's say we had a <comment-card> element that accepted a few fields like subject, description, and time. We've gone ahead and imported one for you, so go ahead and add this to the template also:

html
  <comment-card user="litdeveloper"
                time="12:49 pm"
                subject="Just tried AsyncDirectives!"
                content="Cool stuff, they're really powerful!">
  </comment-card>

Now, since the element accepts time as a string, we can bind the timeAgo directive to that attribute, and it will periodically set the element's time without the outer template needing to re-render:

ts
  time=${timeAgo(timeCreated)}

Congratulations! You now have a useful, working AsyncDirective!

Ideas for further study:

  • Add an optional frequency parameter to the directive, to customize how often the directive re-renders its value. Bonus points for making sure the user can change the frequency after the timer has started!
  • Make an auto mode for the directive that scales the frequency that the timer updates according to the amount of time that has elapsed.
  • Try making a component version of the timeAgo directive. How about a ReactiveController version? When is using one better than the others? (Hint: Lit components can be easily used outside of Lit contexts, but can't be bound to properties/attributes like we did in this example; controllers are useful for sharing functionality inside of components, and async directives are great for sharing functionality outside of components, at the template level).