Events in Lit
Learn Lit events with live examples: @event listeners, this, passive and once options, window listeners, and dispatching events that cross shadow roots.
- 01Listen the Lit wayUse
@eventin a template, know why a new arrow function adds no new listener, and whythisis the component. - 02Put each listener in the right placeSet
passive,once, andcapture, listen on the host or the shadow root, and clean up listeners ondocumentandwindow. - 03Send events the page can useDispatch a bubbling, composed event after
updateComplete, only for what the user did, and readevent.targetacross shadow roots.
How do events work in Lit?
Leaf and Kettle's online menu has an Add button on every tea. Ravi presses Add Sencha. The menu item counts the cup. But the cart at the top of the page should count it too. The item's button lives in the item's shadow root, out of the page's reach.
How does a Lit component hear the click? And how does it tell the rest of the page?
In Lit, you listen with @ in the template, like @click=${this.add}. Lit adds the listener and calls your method with this set to the component. To tell the page, the component dispatches its own event, with bubbles and composed set, so the event can leave its shadow root.
Here is a menu item that does both:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module"> import "./tea-menu-item.js"; document.addEventListener("tea-added", (event) => { console.log(`The page heard: one more ${event.target.name}`); });</script>- Lines 1 to 3 are the import map from lesson 20.1. The name
litmeans Lit 3.3.3, from esm.sh. - Line 4 puts one menu item on the page. Line 6 loads the tea-menu-item.js tab.
- Lines 7 to 9 listen on the whole document for an event called
tea-added. They print the name of the item that sent it.
The tea-menu-item.js tab holds the component:
import { LitElement, html } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {}, cups: { type: Number } };
constructor() {
super();
this.cups = 0;
}
add() {
this.cups += 1;
this.dispatchEvent(new Event("tea-added", { bubbles: true, composed: true }));
}
render() {
return html`<button @click=${this.add}>Add ${this.name}</button>
<span>In cart: ${this.cups}</span>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- Line 4 declares two reactive properties,
nameandcups(lesson 20.2). - Line 17 is the listener:
@clickfollowed by the method to call. - Line 12 counts one more cup. Line 13 sends a new event,
tea-added, from the item itself. - Line 18 shows the count.
Click Add Sencha twice. The item shows In cart: 2. The console prints The page heard: one more Sencha twice.
At Leaf and Kettle, a customer waves to the waiter. The waiter writes it on the pad. Then he calls the order to the kitchen. The kitchen never sees the table. It only hears the call.
- In real life: A customer waving to the waiter
- In JavaScript: A click on the item's button
- In real life: The waiter noting it on the pad
- In JavaScript: add() raising cups
- In real life: Calling "one more Sencha!" to the kitchen
- In JavaScript: this.dispatchEvent(new Event("tea-added", …))
- In real life: The kitchen, which never sees the table
- In JavaScript: The page's listener on document
A Lit component listens with @event=${listener} in its template. Lit adds the listener for you, and this in it is the component. The component speaks with this.dispatchEvent(), and an event with bubbles and composed reaches the page.
Earlier lessons covered events in depth. Lesson 5.3 dispatched them, and lesson 9.1 showed how they change at a shadow root. This lesson is about what Lit adds, and the habits that make Lit components good at events.
What does @click do in a Lit template?
Lesson 20.3 met the @ binding. Lit's docs say it is like calling addEventListener() on the element (Lit). But what does Lit really add? This page counts it.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script> const added = []; const addEventListener = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function (type, listener, options) { if (type === "click") added.push(listener); return addEventListener.call(this, type, listener, options); };</script><script type="module"> import "./tea-menu-item.js"; const item = document.querySelector("tea-menu-item"); await item.updateComplete; for (let n = 1; n <= 3; n++) { item.shadowRoot.querySelector("button").click(); await item.updateComplete; } console.log(`In cart: ${item.cups}. Click listeners added: ${added.length}`); console.log(`What Lit added has a handleEvent() method: ${typeof added[0].handleEvent === "function"}`);</script>- Lines 5 to 12 wrap
addEventListener(). Every click listener added after it goes into the listadded. A plain script runs before any module, so it catches Lit's first one too. - Line 16 waits for the first draw. Lines 17 to 20 click the button three times. Each click draws the item again.
- Lines 21 and 22 print what the list holds.
import { LitElement, html } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {}, cups: { type: Number } };
constructor() {
super();
this.cups = 0;
}
render() {
return html`<button @click=${() => (this.cups += 1)}>Add ${this.name}</button>
<span>In cart: ${this.cups}</span>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);Line 12 is the only change from the overview. The listener is an arrow function written in the template. So every draw makes a new one.
It prints In cart: 3. Click listeners added: 1 and What Lit added has a handleEvent() method: true.
Four draws made four arrow functions. Yet the button got one listener, and it isn't any of them. For each binding, Lit keeps a small object called a part (lesson 20.3). For @, it's an EventPart, and the part itself is the listener. Here is the heart of it:
if (shouldRemoveListener) {
this.element.removeEventListener(this.name, this, oldListener);
}
if (shouldAddListener) {
this.element.addEventListener(this.name, this, newListener);
}
this._$committedValue = newListener;
handleEvent(event) {
if (typeof this._$committedValue === "function") {
this._$committedValue.call(this.options?.host ?? this.element, event);
} else {
this._$committedValue.handleEvent(event);
}
}This is lit-html.ts, lines 2095 to 2118, at lit 3.3.3, without its types. In plain words, line by line:
- Lines 4 and 5 add the listener. The second argument is
this: the part, not your function. - Line 7 keeps the newest value you gave. It runs on every draw, but lines 1 and 4 almost never do.
- Lines 9 to 15 run when the event comes.
handleEvent()calls the function kept on line 7.
Line 1 runs only when you give nothing, or change capture, once, or passive. Line 4 runs when there's no listener yet, or right after line 1 (lines 2069 to 2082). The comment above the class says why: it saves calls to addEventListener() "if the listener changes frequently, such as when an inline function is used as a listener" (lines 2020 to 2030).
Click listeners added: 1 after four draws.Leaf and Kettle has one phone line. Beside it is a note that says who answers today. Each morning, Asha writes a new note. Nobody puts in a new phone line for that.
- In real life: The shop's one phone line
- In JavaScript: Lit's part, the one listener on the button
- In real life: The note saying who answers today
- In JavaScript: The function from the newest draw
- In real life: A fresh note each morning
- In JavaScript: A new arrow function on each draw
- In real life: Putting in a new line
- In JavaScript: Taking the listener off and adding it again
Why it matters: an arrow function in a template costs one small function per draw, and no new listener. Write the one that reads best.
Removing a listener
To take a listener off, give nothing, null, or undefined (Lit). Here a sold-out tea stops listening:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><button id="sold-out">Mark Sencha sold out</button><script type="module"> import "./tea-menu-item.js"; const item = document.querySelector("tea-menu-item"); document.querySelector("#sold-out").onclick = () => (item.soldOut = true);</script>import { LitElement, html, nothing } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {}, cups: { type: Number }, soldOut: { type: Boolean } };
constructor() {
super();
this.cups = 0;
this.soldOut = false;
}
add() {
this.cups += 1;
}
render() {
return html`<button @click=${this.soldOut ? nothing : this.add}>Add ${this.name}</button>
<span>In cart: ${this.cups}</span>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- Line 17 of the tab picks the listener. While the tea is in stock, it's
this.add. Once it's sold out, it'snothing, from line 1. - Line 9 of the page sets the property when you click Mark Sencha sold out.
Click Add Sencha twice: In cart: 2. Click Mark Sencha sold out, then Add Sencha again. It stays at In cart: 2. Lit called removeEventListener() with its part, so the button is deaf now.
What is this in a Lit event listener?
Line 17 of the overview passed this.add with no bind(). Yet this.cups worked. Line 11 of the excerpt says why: Lit calls your function with this.options?.host, or the element when there's no host. This page tries both, with Lit's plain render():
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><div id="plain"></div><div id="hosted"></div><script type="module"> import { html, render } from "lit"; const cart = { owner: "Asha" }; function who() { console.log(this === cart ? "this is Asha's cart" : `this is <${this.localName}>`); } render(html`<button @click=${who}>Plain render</button>`, document.querySelector("#plain")); render(html`<button @click=${who}>With a host</button>`, document.querySelector("#hosted"), { host: cart });</script>- Line 7 takes
htmlandrenderfrom Lit. There's no component on this page. - Line 8 makes a plain object, Asha's cart. Lines 9 to 11 print what
thisis. - Line 12 renders a button with no options. Line 13 renders one with the cart as its host.
Click Plain render. It prints this is <button>. Click With a host. It prints this is Asha's cart.
A LitElement always renders its template with { host: this } (lit-element.ts, line 137, used on line 171). So in a component, this is the component in every function listener of its template. Lit's docs call these listeners bound to the component (Lit). Lesson 20.3 compared it to a doorbell that always rings in the shop that fitted it.
Three things follow:
@click=${this.add}is enough.@click=${() => this.add()}works too, but the arrow adds nothing.- A listener object is different. Lit calls its own
handleEvent()(line 13 of the excerpt), sothisis the object. Use an arrow function inside it, as the next section does. - A listener you add yourself with
addEventListener()never goes through Lit. The browser calls it withthisset to the element it's on (MDN). For those, use an arrow function (arrow functions and this).
How do you make a Lit listener passive, once, or capture?
addEventListener() takes options as its third argument (once, passive and signal):
once: trueruns the listener one time, then takes it off.capture: trueruns it on the event's way down, before the target hears it (capture and bubble).passive: truepromises the listener won't callpreventDefault(). The browser can then scroll at once, without waiting for it (MDN).
An @ binding has no third argument. Lit gives you two other ways. In TypeScript, use the @eventOptions decorator, one of Lit's built-in decorators (Lit):
import { LitElement, html } from "lit";
import { customElement, eventOptions } from "lit/decorators.js";
@customElement("tea-pour")
export class TeaPour extends LitElement {
@eventOptions({ passive: true })
heard(event: Event) {
event.preventDefault();
console.log(`The tray heard it. defaultPrevented: ${event.defaultPrevented}`);
}
render() {
return html`<div @click=${this.heard}>
<button>Pour</button>
</div>`;
}
}- Line 2 takes
eventOptionsfromlit/decorators.js. - Line 6 marks
heard()as passive. Line 13 uses it as usual.
The decorator copies the options onto the method itself: event-options.ts, line 76 is Object.assign(method, options). Then line 5 of the excerpt passes your value as the third argument, the options. So the browser reads passive from the method. Decorators need a compiler such as TypeScript or Babel (lesson 20.2).
In plain JavaScript, give an object with a handleEvent() method and the options (Lit). Try each one here:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-pour></tea-pour><script type="module"> import { LitElement, html } from "lit"; class TeaPour extends LitElement { heard(event) { event.preventDefault(); console.log(`The tray heard it. defaultPrevented: ${event.defaultPrevented}`); } render() { const listener = this.heard; return html`<div @click=${listener}> <button @click=${() => console.log("The button heard it")}>Pour</button> </div>`; } } customElements.define("tea-pour", TeaPour);</script>Click Pour twice. Each click prints The button heard it, then The tray heard it. defaultPrevented: true. The click bubbles up from the button to the tray.
- Lines 8 to 11 are the tray's listener. It calls
preventDefault()and prints whether that worked. - Line 13 is your choice. Line 14 puts it on the tray, a
div. Line 15 gives the button its own listener.
- A method: each click prints
The button heard it, thenThe tray heard it. defaultPrevented: true. The click bubbles up from the button. - once: true: the second click prints only
The button heard it. - capture: true: the tray speaks first, on the click's way down to the button.
- passive: true: it prints
defaultPrevented: false. Chrome ignored the call, and wrote a warning about it in the console.
Line 13 makes a new object on every draw. That's fine. Lit compares only capture, once, and passive (lines 2069 to 2076). If they stay the same, the listener stays. If one changes, Lit takes its listener off and adds it again. And once lasts for the element: after it has run, later draws don't put it back.
Where should a Lit component add its own listeners?
Some listeners don't fit in the template. You may want every click on the whole component, or a key pressed anywhere on the page. Lit's docs give each one a place.
On the host and on the shadow root
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module" src="./tea-menu-item.js"></script>import { LitElement, html } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {} };
constructor() {
super();
this.addEventListener("click", (event) => console.log(`Host: target is <${event.target.localName}>`));
}
createRenderRoot() {
const root = super.createRenderRoot();
root.addEventListener("click", (event) => console.log(`Shadow root: target is <${event.target.localName}>`));
return root;
}
render() {
return html`<button>Add ${this.name}</button>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- Line 8 listens on the host, the component's own element, in the constructor. Lit's docs name the constructor as a good place for that (Lit).
- Lines 11 to 15 listen on the shadow root. The root doesn't exist in the constructor yet. So the item overrides
createRenderRoot(), which makes it (lesson 20.5). Line 14 must return the root. - Line 18 draws a button with no listener at all.
Click Add Sencha. It prints Shadow root: target is <button>, then Host: target is <tea-menu-item>.
The shadow root hears the click first, with the real button. The host hears it next, retargeted to the item itself (lesson 9.1). Neither needs removing. They sit on the component's own nodes, and go away with it (the Lit Cheat Sheet).
On document and window
A menu should close when someone presses Escape, wherever focus is. That key goes to the page, so the menu listens on document. Lit's docs say to add such a listener in connectedCallback() and remove it in disconnectedCallback() (Lit). See what happens without the removal:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-menu.js"; const menu = document.querySelector("tea-menu"); const pressEscape = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); pressEscape(); menu.remove(); pressEscape(); document.body.append(menu); pressEscape();</script>It prints Escape heard. On the page: true, then Escape heard. On the page: false, then true again. The removed menu kept answering, because the document still held its listener.
import { LitElement, html } from "lit";
export class TeaMenu extends LitElement {
#onKey = (event) => {
if (event.key === "Escape") console.log(`Escape heard. On the page: ${this.isConnected}`);
};
connectedCallback() {
super.connectedCallback();
document.addEventListener("keydown", this.#onKey);
}
disconnectedCallback() {
document.removeEventListener("keydown", this.#onKey);
super.disconnectedCallback();
}
render() {
return html`<p>The tea menu is open.</p>`;
}
}
customElements.define("tea-menu", TeaMenu);- Lines 4 to 6 are the listener, a private arrow function field. As an arrow, it keeps
thisas the menu. As a field, it's one function, so the same one can be removed later. - Lines 8 to 11 add it whenever the menu joins the page.
- Lines 13 to 16 remove it whenever the menu leaves. The first choice doesn't have them.
- On the page, line 8 makes a helper that sends Escape to the document. Line 9 presses it, line 10 removes the menu, line 11 presses again, and lines 12 and 13 put the menu back and press once more.
Without the cleanup, it prints Escape heard. On the page: true, then Escape heard. On the page: false, then true again. With it, it prints Escape heard. On the page: true twice.
Ravi gets the morning paper delivered. When he moves out, he cancels it. If he forgets, the paper keeps coming to the empty house. The shop still has his name on its list.
- In real life: Signing up for the morning paper
- In JavaScript: document.addEventListener() in connectedCallback()
- In real life: Moving out
- In JavaScript: The menu leaving the page
- In real life: Cancelling the paper
- In JavaScript: removeEventListener() in disconnectedCallback()
- In real life: Papers piling up at the empty house
- In JavaScript: Escape heard. On the page: false
The document keeps every listener added to it. While it keeps the menu's, the menu can't be freed from memory either. Why add it in connectedCallback(), not the constructor? An element can leave the page and come back, and connectedCallback() runs each time (lesson 3.3). So the listener comes back with it.
Here is every place side by side. Read each row across:
| Where you listen | A click on the item's button arrives with target | Do you remove it? |
|---|---|---|
@click on the button, in the template | The button. | No. Lit adds it, and takes it off when you give nothing. |
@click on a list around the buttons | The button. It's in the same shadow root. | No. Lit looks after it, as above. |
this.addEventListener() in the constructor | The component. The browser hides the button. | No. It goes away with the component. |
The shadow root, in createRenderRoot() | The button. | No. It goes away with the component. |
document or window, in connectedCallback() | The component, like any page code. | Yes, in disconnectedCallback(). |
How do you handle events from a list in Lit?
A list of teas can give each row its own listener. Or one listener on the list can hear them all, because clicks bubble. That's event delegation (event delegation):
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-list></tea-list><script type="module" src="./tea-list.js"></script>import { LitElement, html } from "lit";
export class TeaList extends LitElement {
static properties = { teas: { attribute: false } };
constructor() {
super();
this.teas = ["Sencha", "Assam", "Oolong"];
}
pick(event) {
const button = event.target.closest("button");
if (button) console.log(`Picked ${button.dataset.tea}`);
}
render() {
return html`<ul @click=${this.pick}>
${this.teas.map((tea) => html`<li><button data-tea=${tea}>${tea}</button></li>`)}
</ul>`;
}
}
customElements.define("tea-list", TeaList);- Line 17 puts one
@clickon theul. Line 18 draws the rows withmap()(lesson 20.4), each button with adata-teaattribute. - Line 12 finds the button.
event.targetis the real button here, because the list and the rows share one shadow root.closest()still finds it if the click lands on something inside the button. - Line 13 reads which tea it was.
Click Assam. It prints Picked Assam.
With 100 teas, a listener on each row means 100 listeners. On the list, it's one. Lit's docs say adding listeners is very fast, and usually no problem (Lit). So for a short list, @click=${() => this.add(tea)} on each row is fine, and easier to read. Delegation only works for events that bubble. focus doesn't, so listen for focusin, or on each row.
How do you dispatch an event from a Lit component?
Call this.dispatchEvent() with a new event, as line 13 of the overview did. Two options decide who hears it: bubbles and composed. In Lit apps, a component often sits inside another component's shadow root. Here a menu item sits inside a cart:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module"> import "./tea-cart.js"; document.addEventListener("tea-added", () => console.log("The page heard it"));</script>Click Add Sencha. It prints The cart's list heard it, The cart heard it, then The page heard it. The event bubbled up and left both shadow roots.
import { LitElement, html } from "lit";
import "./tea-menu-item.js";
export class TeaCart extends LitElement {
constructor() {
super();
this.addEventListener("tea-added", () => console.log("The cart heard it"));
}
render() {
return html`<div @tea-added=${() => console.log("The cart's list heard it")}>
<tea-menu-item name="Sencha"></tea-menu-item>
</div>`;
}
}
customElements.define("tea-cart", TeaCart);import { LitElement, html } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {} };
add() {
const event = new Event("tea-added", { bubbles: true, composed: true });
this.dispatchEvent(event);
}
render() {
return html`<button @click=${this.add}>Add ${this.name}</button>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- In tea-cart.js, line 7 listens on the cart itself. Line 11 listens on the
divaround the item.@works for any event name, built in or your own. - Line 12 puts the item inside the cart's shadow root.
- In tea-menu-item.js, line 7 makes the event with your choice of options. Line 8 sends it from the item.
- On the page, line 7 listens on the document.
- bubbles and composed:
The cart's list heard it,The cart heard it,The page heard it. - bubbles only: just
The cart's list heard it. It stops at the edge of the cart's shadow root. - composed only: just
The cart heard it. A composed event that doesn't bubble still reaches the host of each root it leaves (Lit). - neither: nothing at all.
For an event the page should hear, set both, as Lit's docs do (Lit). If only the parent component needs it, bubbles alone keeps it private (lesson 9.2). A listener can also answer back: on a cancelable event, its preventDefault() makes dispatchEvent() return false (lesson 5.3). Lit's context works the same way, with events sent up the tree (lesson 19.4).
What does event.target show outside a Lit component?
Each listener in the playground heard the same event. Did they all see the same target? This cart reports it at every level:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module"> import "./tea-cart.js"; document.addEventListener("tea-added", (event) => { console.log(`The page: target <${event.target.localName}>, path starts at <${event.composedPath()[0].localName}>`); });</script>import { LitElement, html } from "lit";
import "./tea-menu-item.js";
const report = (where, event) =>
console.log(`${where}: target <${event.target.localName}>, path starts at <${event.composedPath()[0].localName}>`);
export class TeaCart extends LitElement {
constructor() {
super();
this.addEventListener("tea-added", (event) => report("The cart", event));
}
render() {
return html`<div @tea-added=${(event) => report("The cart's list", event)}>
<tea-menu-item name="Sencha"></tea-menu-item>
</div>`;
}
}
customElements.define("tea-cart", TeaCart);- Lines 4 and 5 make
report(). It prints the event's target and the first node of its path. - Line 10 reports from the cart itself. Line 14 reports from the list inside its shadow root.
- Lines 7 to 9 of the page print the same, from the document.
Click Add Sencha. It prints The cart's list: target <tea-menu-item>, path starts at <tea-menu-item>, then The cart: target <tea-cart>, path starts at <tea-menu-item>, then The page: target <tea-cart>, path starts at <tea-menu-item>.
composedPath() is the item at every level.A family sits in booth 4. Someone calls out "one more cup!" The waiter across the room hears "booth 4 wants a cup". He can't tell which person spoke. Someone at the same table can.
- In real life: The person who called out
- In JavaScript: The menu item, first in composedPath()
- In real life: The booth
- In JavaScript: The cart's shadow root
- In real life: "Booth 4 wants a cup"
- In JavaScript: event.target is the cart, outside it
- In real life: Someone at the same table
- In JavaScript: The cart's list, which sees the item
That's retargeting. Outside a shadow root, the browser shows the host as the target, so outside code never sees what's inside (lesson 9.1). Every event that leaves a Lit component seems to come from the component (Lit). event.composedPath() lists every node on the trip, so its first one is where the event started (MDN). Lit's docs keep it for rare cases, because it shows a component's insides.
Why it matters: to know which item spoke, listen inside the cart's own shadow root, as line 14 does. There, the target is the item. Exercise 1 asks what the page sees for the click itself.
Why dispatch after updateComplete in Lit?
Lit doesn't draw the moment a property changes. It draws a little later, in a microtask: a small job the browser runs as soon as your code ends (lesson 20.2). So what does a listener see if the item sends its event at once? This page reads the item's screen from the listener:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script type="module"> import "./tea-menu-item.js"; document.addEventListener("tea-added", (event) => { const shown = event.target.shadowRoot.querySelector("span").textContent; console.log(`cups is ${event.target.cups}. The item shows: ${shown}`); });</script>Click Add Sencha. It prints cups is 1. The item shows: In cart: 0. The property changed, but Lit hadn't drawn it yet.
import { LitElement, html } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {}, cups: { type: Number } };
constructor() {
super();
this.cups = 0;
}
async add() {
this.cups += 1;
await this.updateComplete;
this.dispatchEvent(new Event("tea-added", { bubbles: true, composed: true }));
}
render() {
return html`<button @click=${this.add}>Add ${this.name}</button>
<span>In cart: ${this.cups}</span>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- On the page, line 8 reads the text the item shows. Line 9 prints it next to the property.
- In the tab, line 11 makes
add()async. Line 13 waits forupdateComplete, a promise that settles once Lit has drawn the change. Line 14 sends the event after that.
Right away, it prints cups is 1. The item shows: In cart: 0. After updateComplete, it prints cups is 1. The item shows: In cart: 1.
In cart: 0. Wait for updateComplete first, and it reads In cart: 1.Asha calls "order ready!" only when the cup is on the counter. If she called first, Ravi would walk up and find nothing there.
- In real life: Pouring the tea
- In JavaScript: Lit drawing the change
- In real life: Calling "order ready!"
- In JavaScript: this.dispatchEvent()
- In real life: Waiting until the cup is out
- In JavaScript: await this.updateComplete
- In real life: A customer finding an empty counter
- In JavaScript: The listener reading In cart: 0
Lit's docs say the same: when an event tells about a change on screen, await updateComplete first (Lit). Lesson 21.1 follows the whole update, step by step.
When should a Lit component not dispatch an event?
The page may set a property itself, like restoring a saved cart. Should the item announce that? Compare two places for the same event:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Sencha"></tea-menu-item><script> document.addEventListener("tea-added", (event) => console.log(`tea-added, cups: ${event.target.cups}`));</script><script type="module"> import "./tea-menu-item.js"; const item = document.querySelector("tea-menu-item"); await item.updateComplete; item.cups = 3;</script>Nothing prints when the page loads, though line 12 sets cups to 3. Click Add Sencha, and it prints tea-added, cups: 4.
import { LitElement, html } from "lit";
export class TeaMenuItem extends LitElement {
static properties = { name: {}, cups: { type: Number } };
constructor() {
super();
this.cups = 0;
}
add() {
this.cups += 1;
}
updated(changed) {
if (changed.has("cups")) this.dispatchEvent(new Event("tea-added", { bubbles: true, composed: true }));
}
render() {
return html`<button @click=${this.add}>Add ${this.name}</button>
<span>In cart: ${this.cups}</span>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- Lines 5 to 7 of the page listen before anything loads. Line 12 sets cups to 3, as the page's own change.
- Lines 15 to 17 of the tab send the event whenever
cupschanged, whoever changed it.
From the click, nothing prints until you click. Then it prints tea-added, cups: 4. From updated(), it prints tea-added, cups: 0 and tea-added, cups: 3 before any click.
Lit's docs give the rule. Send events for what the user did, or for changes the component finds out later. Don't send them when the owner set a property or an attribute (Lit). The browser works this way: setting input.value fires no input and no change event. A thermostat that rang a bell each time you turned it would only tell you what you just did.
Why it matters: the page already knows about its own change. And a listener that sets the property back could start a loop.
Should a Lit component use CustomEvent or an Event subclass?
So far the listener read event.target. Often it wants data too: which tea? There are two ways to carry it. Lit's docs show both and call either one reasonable (Lit). Lesson 5.3 compared them. Justin Fagnani prefers a class (Stop Using CustomEvent):
- The data sits right on the event, like a click's
clientX, not in adetailbag. - The class is the one place that sets the name and the options, so every copy of the event matches.
- In TypeScript, the class is the event's type.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu-item name="Assam"></tea-menu-item><script type="module"> import { TeaAddedEvent } from "./tea-menu-item.js"; document.addEventListener(TeaAddedEvent.type, (event) => { console.log(`One more ${event.tea}. A TeaAddedEvent: ${event instanceof TeaAddedEvent}`); });</script>import { LitElement, html } from "lit";
export class TeaAddedEvent extends Event {
static type = "tea-added";
constructor(tea) {
super(TeaAddedEvent.type, { bubbles: true, composed: true });
this.tea = tea;
}
}
export class TeaMenuItem extends LitElement {
static properties = { name: {} };
render() {
return html`<button @click=${() => this.dispatchEvent(new TeaAddedEvent(this.name))}>Add ${this.name}</button>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- Lines 3 to 10 of the tab are the class. Line 4 keeps the name. Line 7 passes it and the options to
super(). Line 8 puts the tea on the event. - Line 16 sends a new one on each click.
- On the page, line 6 imports the class. Line 7 listens by its name. Line 8 reads
event.tea.
Click Add Assam. It prints One more Assam. A TeaAddedEvent: true.
The same event as a CustomEvent puts the tea in detail:
// Sending it
this.dispatchEvent(new CustomEvent("tea-added", { detail: { tea: this.name }, bubbles: true, composed: true }));
// Hearing it
cart.addEventListener("tea-added", (event) => console.log(event.detail.tea));Line 2 puts the tea in detail, and line 5 reads it from there. In TypeScript, add a class to HTMLElementEventMap, the list of events every HTML element has:
class TeaAddedEvent extends Event { static type = "tea-added"; tea: string; constructor(tea: string) { super(TeaAddedEvent.type, { bubbles: true, composed: true }); this.tea = tea; }} declare global { interface HTMLElementEventMap { "tea-added": TeaAddedEvent; }} const cart = document.createElement("tea-cart");cart.addEventListener("tea-added", (event) => { console.log(event.tea); // ^?});document.addEventListener("tea-added", (event) => console.log(event.tea)); export {};- Lines 11 to 15 add the event to the list. So on line 19,
event.teais astring. - Line 22 has an error on purpose.
documentisn't an HTML element, so its list doesn't havetea-added, andeventis a plainEvent. Fordocumentandwindowtoo, useGlobalEventHandlersEventMap, as lesson 5.3 did.
Building a tea cart that hears every menu item
Now the whole menu: a cart with three items. It uses every lesson of this module: reactive properties, a property binding, a list, static styles, and events.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module"> import "./tea-cart.js"; document.addEventListener("tea-cart-change", (event) => { console.log(event.target.shadowRoot.querySelector("p").textContent); });</script>import { LitElement, html, css } from "lit";
import "./tea-menu-item.js";
export class TeaCart extends LitElement {
static properties = { teas: { attribute: false }, counts: { state: true } };
static styles = css`p { font-weight: bold; }`;
constructor() {
super();
this.teas = ["Sencha", "Assam", "Oolong"];
this.counts = {};
}
async add(event) {
this.counts = { ...this.counts, [event.tea]: (this.counts[event.tea] ?? 0) + 1 };
await this.updateComplete;
this.dispatchEvent(new Event("tea-cart-change", { bubbles: true, composed: true }));
}
render() {
const total = Object.values(this.counts).reduce((sum, cups) => sum + cups, 0);
return html`<div @tea-added=${this.add}>
${this.teas.map((tea) => html`<tea-menu-item name=${tea} .cups=${this.counts[tea] ?? 0}></tea-menu-item>`)}
</div>
<p>Cups in the cart: ${total}</p>`;
}
}
customElements.define("tea-cart", TeaCart);import { LitElement, html, css } from "lit";
export class TeaAddedEvent extends Event {
static type = "tea-added";
constructor(tea) {
super(TeaAddedEvent.type, { bubbles: true, composed: true });
this.tea = tea;
}
}
export class TeaMenuItem extends LitElement {
static properties = { name: {}, cups: { type: Number } };
static styles = css`:host { display: flex; gap: 8px; align-items: center; margin: 4px 0; }`;
constructor() {
super();
this.cups = 0;
}
render() {
return html`<button @click=${() => this.dispatchEvent(new TeaAddedEvent(this.name))}>Add ${this.name}</button>
<span>In cart: ${this.cups}</span>`;
}
}
customElements.define("tea-menu-item", TeaMenuItem);- In tea-cart.js, line 22 is one
@tea-addedon thedivaround the items. Inside the cart's shadow root, the target is the item that spoke. - Line 15 makes a new
countsobject, so Lit sees the change (lesson 20.2). Line 16 waits for the draw. Line 17 tells the page. - Line 23 passes each count down with
.cups(lesson 20.3). Line 25 shows the total. - In tea-menu-item.js, line 22 only asks for one more cup. It never changes
cupsitself, and it sends nothing when the cart sets it. Line 14 is its static style (lesson 20.5).
Click Add Sencha, Add Assam, then Add Sencha. The console prints Cups in the cart: 1, Cups in the cart: 2, and Cups in the cart: 3. The items show In cart: 2, In cart: 1, and In cart: 0.
Events go up, and properties come down (lesson 18.4). The items never talk to each other. The cart sits between them and keeps the counts, the way the shelf of lesson 18.4 did for its badge and tiles.
- A click on the Add button the component draws
- Typing in a search box inside the component
- A click on any of 50 rows the component draws
- Any click on the component, even on the children the page slots into it
- Arrow keys pressed anywhere inside the component
- Escape pressed anywhere on the page, to close a menu
- The window changing size
- A click outside the component, to close a popup
Sort each listener into the place a Lit component should add it.
Common mix-ups
- "A new arrow function in the template adds a new listener on every draw." No. Lit's part is the one listener. It only swaps the function it calls. Four draws printed
Click listeners added: 1. - "@click needs bind(this) or an arrow function, or this is lost." No. A LitElement renders with
{ host: this }, and Lit calls every listener function with that host. - "@eventOptions works in any JavaScript file." No. It's a decorator, so it needs TypeScript or Babel. In plain JavaScript, use an object with
handleEvent()and the options. - "A listener on document can go in the constructor and stay there." No. Add it in
connectedCallback()and remove it indisconnectedCallback(), or the removed menu keeps answering. - "Outside the component, event.target is the button that was clicked." No. Outside a shadow root, the target is the host. Only
composedPath()shows where the event started. - "bubbles: true is enough for the page to hear it." No. Without
composed, the event stops at the edge of the shadow root it started in. - "You can rename an event after you make it, with event.type." No.
typeis read-only. Setting it in a class that extendsEventthrows aTypeError. Pass the name tosuper(). - "A component should announce every change to its properties." No. Announce what the user did. When the page sets a property, the page already knows.
Practice exercises
The cart in the tea-cart.js tab draws the overview's menu item. Read the page without running it. What does the console print when you click Add Sencha?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<tea-cart></tea-cart>
<script type="module">
import "./tea-cart.js";
document.addEventListener("click", (event) => {
console.log(`${event.target.localName} ${event.composedPath()[0].localName}`);
});
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module"> import "./tea-cart.js"; document.addEventListener("click", (event) => { console.log(`${event.target.localName} ${event.composedPath()[0].localName}`); });</script>It prints tea-cart button. The click left two shadow roots. At the document, the target is the outer host, the cart. The path starts at the button, where the click began.
The page draws three teapot buttons five times. Read it without running it. What does the console print?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<tea-teapots></tea-teapots>
<script>
const added = [];
const addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (type, listener, options) {
if (type === "click") added.push(listener);
return addEventListener.call(this, type, listener, options);
};
</script>
<script type="module">
import "./tea-teapots.js";
const pots = document.querySelector("tea-teapots");
for (let n = 1; n <= 5; n++) {
pots.pours = n;
await pots.updateComplete;
}
console.log(`Click listeners added: ${added.length}`);
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-teapots></tea-teapots><script> const added = []; const addEventListener = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function (type, listener, options) { if (type === "click") added.push(listener); return addEventListener.call(this, type, listener, options); };</script><script type="module"> import "./tea-teapots.js"; const pots = document.querySelector("tea-teapots"); for (let n = 1; n <= 5; n++) { pots.pours = n; await pots.updateComplete; } console.log(`Click listeners added: ${added.length}`);</script>It prints Click listeners added: 3. map() makes three buttons, each with its own @click binding, so three parts. Each draw only hands every part a new arrow function.
Click Add Sencha. The cups go up, but the page prints nothing. Fix the item so the page hears it.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module"> import "./tea-cart.js"; document.addEventListener("tea-added", (event) => { console.log(`The page heard tea-added from <${event.target.localName}>`); });</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cart></tea-cart><script type="module"> import "./tea-cart.js"; document.addEventListener("tea-added", (event) => { console.log(`The page heard tea-added from <${event.target.localName}>`); });</script>Only line 13 of the tea-menu-item.js tab changes, to { bubbles: true, composed: true }. Now the event leaves the cart's shadow root, and the page prints The page heard tea-added from <tea-cart>.
This menu has a disconnectedCallback(), yet it prints four lines, one with On the page: false. Fix the tea-menu.js tab.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-menu.js"; const menu = document.querySelector("tea-menu"); const pressEscape = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); pressEscape(); menu.remove(); pressEscape(); document.body.append(menu); pressEscape();</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-menu></tea-menu><script type="module"> import "./tea-menu.js"; const menu = document.querySelector("tea-menu"); const pressEscape = () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })); pressEscape(); menu.remove(); pressEscape(); document.body.append(menu); pressEscape();</script>The tea-menu.js tab changes: lines 4 to 6 become the field #onKey = (event) => { … }, and lines 10 and 14 add and remove this.#onKey. Each bind() made a new function, so nothing was ever removed. Now it prints Escape heard. On the page: true twice.
Clicking a tea does nothing. Make every button in the list send tea-added, with one listener for the whole list.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-list></tea-list><script type="module"> import "./tea-list.js"; document.addEventListener("tea-added", (event) => console.log(`One more ${event.tea}`));</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-list></tea-list><script type="module"> import "./tea-list.js"; document.addEventListener("tea-added", (event) => console.log(`One more ${event.tea}`));</script>Only line 18 of the tea-list.js tab changes, to <ul @click=${this.pick}>. Every click bubbles up to the list. pick() finds the button, and sends TeaAddedEvent with its tea. Click Oolong, and it prints One more Oolong.
The rating prints two lines before anyone clicks. Only a click should send change. Fix the tea-cup-rating.js tab.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating></tea-cup-rating><script> document.addEventListener("change", (event) => console.log(`change: ${event.target.value} cups`));</script><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; rating.value = 3;</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating></tea-cup-rating><script> document.addEventListener("change", (event) => console.log(`change: ${event.target.value} cups`));</script><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; rating.value = 3;</script>The tea-cup-rating.js tab changes: pick() becomes async, sets the value, waits for updateComplete, and sends change. updated() is gone. Nothing prints when the page loads. Click the fourth cup, and it prints change: 4 cups.
Check your understanding
Question 1 of 8This page has a menu item and a listener on the document. You click Add Sencha once. What does the console print?
Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } } </script> <tea-menu-item name="Sencha"></tea-menu-item> <script type="module"> import "./tea-menu-item.js"; document.addEventListener("tea-added", (event) => { console.log(`The page heard: one more ${event.target.name}`); }); </script>Choose an answer to see the explanation.
Question 2 of 8A template has @click=${() => (this.cups += 1)}, so every draw makes a new function. The page draws it four times. How many times did Lit call addEventListener()?
Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } } </script> <tea-menu-item name="Sencha"></tea-menu-item> <script> const added = []; const addEventListener = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function (type, listener, options) { if (type === "click") added.push(listener); return addEventListener.call(this, type, listener, options); }; </script> <script type="module"> import "./tea-menu-item.js"; const item = document.querySelector("tea-menu-item"); await item.updateComplete; for (let n = 1; n <= 3; n++) { item.shadowRoot.querySelector("button").click(); await item.updateComplete; } console.log(`In cart: ${item.cups}. Click listeners added: ${added.length}`); console.log(`What Lit added has a handleEvent() method: ${typeof added[0].handleEvent === "function"}`); </script>Choose an answer to see the explanation.
Question 3 of 8Inside a LitElement, why is this the component in a method used as @click=${this.add}?
Choose an answer to see the explanation.
Question 4 of 8In a plain JavaScript file with no decorators, how do you make a Lit listener passive?
Choose an answer to see the explanation.
Question 5 of 8A menu item inside a cart's shadow root dispatches new Event("tea-added", { composed: true }), with no bubbles. Who hears it?
Choose an answer to see the explanation.
Question 6 of 8A Lit menu closes when someone presses Escape anywhere on the page. Where should its keydown listener go?
Choose an answer to see the explanation.
Question 7 of 8Why does add() write await this.updateComplete before this.dispatchEvent(...)?
Choose an answer to see the explanation.
Question 8 of 8The page restores a saved cart with item.cups = 3. Should the item dispatch tea-added?
Choose an answer to see the explanation.
Key takeaways
- Listen with @event=${listener} in the template. The value is a function or an object with handleEvent().
- Lit adds one part per binding as the listener. A new function on each draw adds no new listener.
- Give nothing, null, or undefined to take the listener off.
- this in a listener function is the component, because LitElement renders with { host: this }.
- Set once, capture, and passive with an object in JavaScript, or with @eventOptions in TypeScript.
- Listen on the host in the constructor, on the shadow root in createRenderRoot(), and on document or window only in connectedCallback(), removed in disconnectedCallback().
- Dispatch with bubbles and composed so the page hears it. Outside, event.target is your component.
- Await updateComplete before an event about the screen, and send events for what the user did.
That ends module 20. A Lit component declares its properties (20.2), draws them with a template (20.3), shows parts and lists (20.4), and styles itself with one shared sheet (20.5). Now it talks to the page, too.
Remember the one-liner.
Listen with @ in the template, and speak with an event that bubbles and is composed, once the screen shows the change.
Sources
The facts on this page come from these docs, posts, and source files:
- Events, Lit.
- Expressions, Lit.
- lit-html.ts, at lit 3.3.3, Lit.
- lit-element.ts, at lit 3.3.3, Lit.
- Decorators, Lit.
- event-options.ts, at lit 3.3.3, Lit.
- EventTarget: addEventListener() method, MDN.
- The Lit Cheat Sheet, Elliott Marquez, Lit.
- Element: focusin event, MDN.
- Event: composedPath() method, MDN.
- Stop Using CustomEvent, Justin Fagnani.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: The Lit update lifecycle, the next lesson of the Lit stage. It follows one update from a property change to the drawn screen.