completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Mixins, controllers, and behaviors

Learn web component mixins and reactive controllers: write mixins that call super, give your base class a controller host, and pick the right pattern.

By the end, you can
  • 01
    Write and stack mixinsWrite a mixin as a function from a class to a subclass, call super in every hook, and apply each mixin once.
  • 02
    Write and host controllersWrite a controller that starts in hostConnected() and stops in hostDisconnected(), and give your own base class the host API Lit controllers use.
  • 03
    Pick a patternChoose a base class, a mixin, a controller, or a behavioral element for a feature, and build bigger pieces from small ones.

How do you share code between web components?

Asha runs the order screen at Leaf and Kettle. Today two parts of it need new skills. The cup must join the order form. The form code lives in TeaFormControl, but the cup already extends TeaElement. A class has only one parent.

The flavor toolbar has arrow keys. Its constructor wires them by hand, and they never stop. The tabs want the same keys. How can Asha share this code without one tall chain of classes?

Use a mixin when the component itself must become more, like a form control. A mixin is a function that takes a class and returns a subclass of it. Use a controller when a separate piece must follow the component's life, like arrow keys. A controller is an object the component owns, and the base class calls it when the component connects, updates, and disconnects.

Here are both, in the tea kit. Click Green, then press Right Arrow:

The kit's toolbar and cup on one formPop out in the code editor (opens in a new tab)HTML
<form>  <tea-flavors label="Flavors">    <button type="button">Green</button>    <button type="button">Black</button>    <button type="button">Oolong</button>  </tea-flavors>  <p><tea-cup name="cup" size="4" roast="dark">Hojicha</tea-cup></p></form><script type="module">  import "./tea-kit/index.js";  console.log("The form sends:", new FormData(document.forms[0]).get("cup"));</script>
ResultLoading…
  • Line 2 is the toolbar. It gets its arrow keys from two controllers.
  • Line 7 is the cup, with the name cup. A mixin made it a form control.
  • Line 11 prints what the form would send for the cup.

It prints The form sends: 4 dark. Right Arrow moves focus from Green to Black, and the whole row is one Tab stop. Here are the two shapes, in the kit's own code:

A mixin in extends, and a controller in a fieldJavaScript
class TeaCup extends FormAssociated(TeaElement) {
  // ...
}

class TeaFlavors extends TeaElement {
  #roving = new RovingController(this, { items: () => this.#buttons() });
  // ...
}
  • Line 1: the cup's parent is whatever FormAssociated(TeaElement) returns. That's a mixin.
  • Line 6: the toolbar keeps a RovingController in a field. That's a controller.
Two rows. The top row is a chain of three cards joined by arrows: TeaCup, then FormAssociatedElement, then TeaElement. Each class extends the next one. The bottom row has a card for tea-flavors on the left, with two arrows from it to two cards on the right: ChildrenController and RovingController. They are separate objects the toolbar owns.A mixin: the cup is a form controlTeaCupFormAssociatedElementTeaElementeach class extends the nextControllers: the toolbar has themtea-flavorsChildrenControllerRovingControllerthe hostseparate objects it owns
A mixin puts a class inside the cup's own chain, so the cup is a form-associated element. The toolbar has two controllers: separate objects it keeps in fields.
Real-life analogyAdd-ins and a clip-on timer

Asha makes chai. She blends milk and ginger into the tea, and they become part of the drink. Then she clips a timer onto the pot. The timer stays its own thing. She can clip it onto any pot, and take it off again.

In real life: Milk and ginger, blended into the tea
In JavaScript: Mixins, inside the class chain
In real life: The chai you serve
In JavaScript: The finished class, like TeaCup
In real life: A timer clipped onto the pot
In JavaScript: A controller the component owns
In real life: Clipping the same timer onto another pot
In JavaScript: new RovingController(this) in another component
The main idea

A mixin is a function from a class to a subclass. The component is what the mixin adds. A controller is an object the component owns. The base class calls its hostConnected(), hostUpdate(), hostUpdated(), and hostDisconnected(). Pick a controller, unless the feature adds public API or needs a finer hook.

Lesson 17.4 began a mixin, and lesson 18.5 used one from Lit. This lesson writes mixins for the kit, then adds controllers to TeaElement, the base class from lessons 19.1 and 19.2.

What is a mixin in JavaScript?

A mixin is a function that takes a class and returns a new class that extends it. Lit's docs call it a subclass factory (Lit). It's plain JavaScript, so it runs anywhere:

One mixin, two different parentsPop out in the code editor (opens in a new tab)JavaScript
const Priced = (Base) =>
  class extends Base {
    priceTag() {
      return `${this.name}: ${this.price} EUR`;
    }
  };

class Tea {
  name = "Sencha";
  price = 4;
}
class Kettle {
  name = "Kettle";
  price = 30;
}

class TeaForSale extends Priced(Tea) {}
class KettleForSale extends Priced(Kettle) {}

console.log(new TeaForSale().priceTag());
console.log(new KettleForSale().priceTag());
console.log(Object.getPrototypeOf(TeaForSale) === Object.getPrototypeOf(KettleForSale));
  • Lines 1 to 6 are the mixin. It takes Base and returns a class that extends it, with one more method.
  • Lines 8 to 15 are two classes with nothing in common: a tea and a kettle.
  • Lines 17 and 18 pass each one to the mixin, and extend what comes back.
  • Line 22 asks whether the two classes share one middle class.

It prints Sencha: 4 EUR, Kettle: 30 EUR, and false. One mixin worked on two parents. Each call made a new class, so the two middles are different classes. Why it matters: a mixin adds code to a class that already has a parent. That's the cup's problem.

The word extends can take any expression that gives a class, even a function call (MDN, and the extends chain). The JavaScript course's mixins lesson builds the pattern from the start.

Big libraries build controls this way, one behavior per mixin. Material Web's checkbox stacks four mixins on LitElement: ARIA, validation, forms, and internals (lines 35 to 39).

Why must every mixin call super?

A mixin often replaces a callback, like connectedCallback(). Its class sits between the component and the parent. The browser calls the element's callback once, and JavaScript finds the outermost class's version first. The others run only if each one calls super.connectedCallback().

The mixins.js tab holds three small mixins. Counted counts notes. Focusable makes a note a Tab stop. Ordered builds on Counted. The note stacks the first two on TeaElement. Try both:

Playground: one mixin forgets super
A note made of two mixins and TeaElementPop out in the code editor (opens in a new tab)HTML
<tea-note>Sencha is ready</tea-note><script type="module">  import "./tea-note.js";  const note = document.querySelector("tea-note");  await note.updateComplete;  console.log("tabIndex:", note.tabIndex);  console.log("Drawn:", note.shadowRoot.textContent || "nothing");</script>
ResultLoading…
Try it yourself
The call reaches every class

Focusable calls super, so Counted runs. Counted calls super, so TeaElement asks for the first draw. All three did their part.

Only line 15 of the mixins.js tab changes.
  • Line 1 is a note. Line 5 waits for its first draw. Lines 6 and 7 print its tabIndex and what it drew.
  • In the tea-note.js tab, line 4 stacks Focusable on Counted, on TeaElement.

With every super, it prints Counted: 1, Focusable: a Tab stop, tabIndex: 0, and Drawn: Note: Sencha is ready. When Focusable forgets, it prints Focusable: a Tab stop, tabIndex: 0, and Drawn: nothing. The note is blank, and the console shows no error.

Two rows of four cards: TeaNote, Focusable, Counted, and TeaElement. In the top row, labeled Every hook calls super, arrows join all four. In the bottom row, labeled Focusable forgets super, an arrow joins TeaNote to Focusable and stops there. Counted and TeaElement are faded and crossed out, with the words never run under them.Every hook calls superTeaNoteFocusableCountedTeaElementFocusable forgets superTeaNoteFocusableCountedTeaElementnever run
The browser calls the note's connectedCallback() once. Each super call hands it to the next class. When Focusable forgets, Counted and TeaElement never run, and nothing says so.

Focusable still did its own job. But the call stopped there. Counted never counted. TeaElement never asked for a draw, so render() never ran. Lit's docs say a mixin should always call super in the custom element callbacks (Lit).

Real-life analogyAn order slip down the kitchen line

In the Leaf and Kettle kitchen, an order slip goes down a line of cooks. Each one does a part and passes it on. One day the cook at the grill puts the slip in his pocket. The cooks after him never see the order. Nobody shouts. The plate just never comes.

In real life: The order slip
In JavaScript: The connectedCallback() call
In real life: Passing the slip on
In JavaScript: super.connectedCallback()
In real life: The cook who pockets it
In JavaScript: The mixin that forgets super
In real life: The cooks after him
In JavaScript: The mixins below it, and TeaElement

Call super in every hook you replace: the four lifecycle callbacks, and attributeChangedCallback() too. Exercise 3 forgets it there. Where you call it matters as well. Code before super runs ahead of the classes below. Code after it runs once they have finished. Material Web's focusable mixin calls super first, then sets its tabindex (lines 74 to 77).

One more catch. HTMLElement has no connectedCallback() of its own. A mixin meant for any element calls it with ?., which skips a call to nothing:

A mixin that works straight on HTMLElementPop out in the code editor (opens in a new tab)JavaScript
console.log("connectedCallback" in HTMLElement.prototype);

const Logged = (Base) =>
  class extends Base {
    connectedCallback() {
      super.connectedCallback?.();
      console.log("Logged: connected");
    }
  };

customElements.define("tea-plain", class extends Logged(HTMLElement) {});
document.body.append(document.createElement("tea-plain"));
  • Line 1 asks whether HTMLElement.prototype has a connectedCallback.
  • Line 6 calls the parent's callback only if there is one.
  • Lines 11 and 12 define an element right on HTMLElement, and add one to the page.

It prints false, then Logged: connected. Without the ?., line 6 throws a TypeError: there's nothing to call. Lit's docs write super.updated?.() for the same reason (Lit).

Does the order of mixins matter?

Yes. The mixin written outside wraps the ones inside it. Its code before super runs first, and its code after super runs last. Two add-ins on a tea show it:

Milk outside, ginger insidePop out in the code editor (opens in a new tab)JavaScript
const AddIn = (name) => (Base) =>
  class extends Base {
    brew() {
      console.log(`${name}: before super`);
      super.brew();
      console.log(`${name}: after super`);
    }
  };

class Tea {
  brew() {
    console.log("Tea: brew");
  }
}

class Chai extends AddIn("Milk")(AddIn("Ginger")(Tea)) {}
new Chai().brew();
  • Lines 1 to 8 make a mixin for any add-in name. Line 4 prints before super, and line 6 after it.
  • Line 16 puts Milk outside Ginger, and Ginger outside Tea.

It prints Milk: before super, Ginger: before super, Tea: brew, Ginger: after super, and Milk: after super.

Real-life analogyA set of nesting dolls

To reach the smallest nesting doll, you open the biggest one first. To put them away, you close the smallest one first, and the biggest one last.

In real life: The biggest doll
In JavaScript: The outer mixin, Milk
In real life: Opening them, outside in
In JavaScript: Code before super
In real life: The smallest doll
In JavaScript: The base class, Tea
In real life: Closing them, inside out
In JavaScript: Code after super

Why it matters: when two mixins change the same thing after super, the outer one has the last word.

What happens when a mixin is applied twice?

A mixin can bring another one with it. Ordered builds on Counted, on line 22 of mixins.js. Now a note adds Counted again, on top:

Playground: Counted once, twice, and with dedupe()
Two notes, and the chain of classes behind themPop out in the code editor (opens in a new tab)HTML
<tea-note>Sencha</tea-note><tea-note>Oolong</tea-note><script type="module">  import { TeaNote } from "./tea-note.js";  const chain = [];  for (let step = TeaNote; step !== HTMLElement; step = Object.getPrototypeOf(step)) chain.push(step.name);  console.log(chain.join(" > "));</script>
ResultLoading…
Try it yourself
Counted comes once, inside Ordered

Ordered builds on Counted, so the chain holds Counted once. Two notes count to 2.

Applied twice changes line 4 of the tea-note.js tab. With dedupe() changes the mixins.js tab: lines 5 and 12 wrap Counted in dedupe().
  • Lines 1 and 2 are two notes. Lines 5 to 7 print the chain of classes behind them.

With Ordered alone, two notes count to 2. Applied twice, the chain holds CountedElement twice, and two notes count to 4. With dedupe(), they count to 2 again, and the chain is TeaNote > OrderedElement > CountedElement > TeaElement > ReactiveTea. Here is the dedupe.js tab:

dedupe.js: apply a mixin only once per chainJavaScript
const applied = new WeakMap();

export const dedupe = (mixin) => (Base) => {
  for (let step = Base; step; step = Object.getPrototypeOf(step)) {
    if (applied.get(step) === mixin) return Base;
  }
  const Mixed = mixin(Base);
  applied.set(Mixed, mixin);
  return Mixed;
};
  • Line 1 keeps a note of which mixin made each class. A WeakMap doesn't keep the classes alive (WeakMap keys).
  • Lines 4 to 6 walk up from Base. If the mixin made one of those classes, line 5 hands back Base unchanged.
  • Lines 7 and 8 apply the mixin, and note which class it made.

open-wc's dedupeMixin() works the same way (lines 1 to 34). Its docs show a logging mixin that logs twice without it (open-wc). ING's Lion wraps its SlotMixin in it (line 366).

Stacking is harder in TypeScript. Lit's docs show how to type the class a mixin takes. They also show why you cast what it returns: TypeScript can't describe a class expression that extends one with private or protected members, like LitElement (Lit).

How do you mix TeaElement and TeaFormControl?

Back to the cup. Lesson 17.4 built TeaFormControl on HTMLElement. Lesson 19.1 left combining it with TeaElement for this lesson. TeaFormControl writes its own attribute getters and its own changed() step. On TeaElement, a mixin gets both for free:

  • declared attributes, from lesson 19.2;
  • requestUpdate(), which every change already calls.
form-associated.js: the FormAssociated mixinJavaScript
import { attachInternals } from "./internals.js";

export const FormAssociated = (Base) =>
  class FormAssociatedElement extends Base {
    static formAssociated = true;
    static attributes = {
      name: { reflect: true, fallback: "" },
      disabled: { type: Boolean, reflect: true },
    };
    #internals = attachInternals(this);

    get internals() {
      return this.#internals;
    }

    get form() {
      return this.#internals.form;
    }

    requestUpdate(name, oldValue) {
      super.requestUpdate(name, oldValue);
      this.#internals.setFormValue(this.formValue());
    }

    formValue() {
      return null;
    }
  };
  • Line 3 takes Base. Line 4 returns a subclass of it, FormAssociatedElement.
  • Line 5 tells the browser the element joins forms (lesson 16.1).
  • Lines 6 to 9 declare name and disabled. TeaElement makes their properties.
  • Line 10 attaches the internals. attachInternals() works only once on an element, so line 12 hands them on to subclasses.
  • Lines 20 to 23 replace requestUpdate(). Line 21 asks for an update, as before. Line 22 hands the form the new value at once.
  • Lines 25 to 27 are a hook: the value to send. null sends nothing.

The cup uses it on line 4 of tea-kit/tea-cup.js: class TeaCup extends FormAssociated(TeaElement). Its formValue() gives the order, like 4 dark. Why replace requestUpdate(), and not updated()? Try both:

Playground: when the mixin hands the form its value
A cup on a form, read before and after a clickPop out in the code editor (opens in a new tab)HTML
<form>  <tea-cup name="cup" size="4" roast="dark">Hojicha</tea-cup>  <button type="button" id="bigger">Bigger</button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("form");  const cup = document.querySelector("tea-cup");  console.log("The form sends:", new FormData(form).get("cup"));  document.querySelector("#bigger").addEventListener("click", () => {    cup.size += 1;    console.log("The form sends:", new FormData(form).get("cup"));  });</script>
ResultLoading…
Try it yourself
The form has each change at once

Every property change calls requestUpdate(), and the mixin hands the form the new value right there. So the click handler reads 5 dark.

Only lines 32 and 33 of the tea-kit/form-associated.js tab change.
  • Line 9 reads the form once, as the page starts.
  • Lines 10 to 13 make the cup bigger, then read the form again, in the same click.

In requestUpdate(), it prints The form sends: 4 dark. After a click, it prints The form sends: 5 dark. In updated(), it prints The form sends: null, then The form sends: 4 dark: one step behind.

Material Web's form mixin also does it in requestUpdate(), so form data is ready for listeners that read it right away (lines 252 to 264). Material Web makes its internals in a getter, not a field. Lit's constructor already calls requestUpdate() (line 1055), before a mixin's fields exist (lines 60 to 69).

TeaFormControl stays, for tea-toggle, tea-field, and the other controls built on HTMLElement. It also handles validation, reset, and the Back button. The mixin starts smaller. Exercise 4 uses it on the badge.

What is a reactive controller?

Now the toolbar. Here is its constructor, as lesson 14.2 left it:

tea-flavors.js from lesson 14.2: the keys wired by handJavaScript
  constructor() {
    super();
    this.#internals.role = "toolbar";
    this.attachShadow({ mode: "open" });
    this.shadowRoot.adoptedStyleSheets = [base, sheet];
    this.shadowRoot.append(template.content.cloneNode(true));
    const slot = this.shadowRoot.querySelector("slot");
    this.#roving = new RovingFocus(this, () => slot.assignedElements().filter((element) => element.localName === "button"));
    slot.addEventListener("slotchange", () => this.#roving.update());
    new MutationObserver(() => this.#roving.update()).observe(this, { subtree: true, attributeFilter: ["disabled"] });
  }
  • Line 8 makes a RovingFocus helper. Its constructor adds two listeners (lesson 14.2).
  • Line 9 calls update() when the slot's buttons change. Line 10 calls it when one switches off.

Every component with arrow keys repeats those three lines. And nothing ever stops them. Here that's harmless, since they only listen to the toolbar itself. A helper that listens to the whole page would keep working after the toolbar is gone.

A reactive controller packs that work into an object. The component owns it, like the timer clipped onto the pot. The host calls up to four hooks on it (Lit):

  • hostConnected(): the host joined the page. Start listeners and observers here.
  • hostUpdate(): an update is about to draw.
  • hostUpdated(): the update has drawn.
  • hostDisconnected(): the host left the page. Stop what hostConnected() started.

Lit added controllers in Lit 2.0, for sharing stateful logic between components (Lit). Here is the kit's RovingController, lesson 14.2's helper as a controller:

controllers.js: RovingController's hooksJavaScript
export class RovingController {
  #current = null;
  #typed = "";
  #typedAt = -Infinity;
  #onFocusin = (event) => this.#focusin(event);
  #onKeydown = (event) => this.#keydown(event);

  constructor(host, { items, vertical = false, wrap = true, typeaheadDelay = 500 }) {
    Object.assign(this, { host, items, vertical, wrap, typeaheadDelay });
    host.addController(this);
  }

  hostConnected() {
    this.host.addEventListener("focusin", this.#onFocusin);
    this.host.addEventListener("keydown", this.#onKeydown);
  }

  hostDisconnected() {
    this.host.removeEventListener("focusin", this.#onFocusin);
    this.host.removeEventListener("keydown", this.#onKeydown);
  }

  hostUpdated() {
    this.update();
  }
  • Lines 5 and 6 keep the two listeners in fields.
  • Line 10 adds the controller to its host.
  • Lines 13 to 16 add the listeners when the host joins the page. Lines 18 to 21 take the same two off when it leaves.
  • Lines 23 to 25 fix the tab stops after every update. The host never calls update() itself.

The rest of the file is lesson 14.2's key handling, unchanged. A second controller watches the buttons:

controllers.js: ChildrenController asks for an updateJavaScript
export class ChildrenController {
  #observer;

  constructor(host) {
    this.host = host;
    this.#observer = new MutationObserver(() => host.requestUpdate());
    host.addController(this);
  }

  hostConnected() {
    this.#observer.observe(this.host, { childList: true, subtree: true, attributeFilter: ["disabled"] });
  }

  hostDisconnected() {
    this.#observer.disconnect();
  }
}
  • Line 6 makes an observer that asks the host for an update.
  • Lines 10 to 12 watch the host's children while it's on the page. Lines 14 to 16 stop watching.

Lit Labs ships the same idea as MutationController. It observes in hostConnected() and stops in hostDisconnected() (lines 123 to 131). The toolbar now needs two lines of wiring:

tea-flavors.js: two controllers in place of the wiringJavaScript
  #internals = attachInternals(this);
  #children = new ChildrenController(this);
  #roving = new RovingController(this, { items: () => this.#buttons() });

  constructor() {
    super();
    this.#internals.role = "toolbar";
  }

  render() {
    this.#internals.ariaLabel = this.label;
    this.#internals.ariaOrientation = this.orientation;
    this.#roving.vertical = this.orientation === "vertical";
  }
  • Lines 2 and 3 make the two controllers. That's all the wiring.
  • Lines 10 to 14 copy label and orientation to the toolbar and to its controller.

Click Green and press Right Arrow. Remove the toolbar, put it back, and try again. Then add Herbal, and press Left Arrow from Green:

The toolbar off the page, back, and with a new buttonPop out in the code editor (opens in a new tab)HTML
<tea-flavors label="Flavors">  <button>Green</button>  <button>Black</button>  <button>Oolong</button></tea-flavors><p>  <button id="remove">Remove the toolbar</button>  <button id="back">Put it back</button>  <button id="add">Add Herbal</button></p><script type="module">  import "./tea-kit/index.js";  const flavors = document.querySelector("tea-flavors");  const row = document.querySelector("p");  flavors.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));  row.querySelector("#remove").onclick = () => flavors.remove();  row.querySelector("#back").onclick = () => row.before(flavors);  row.querySelector("#add").onclick = () => flavors.insertAdjacentHTML("beforeend", "<button>Herbal</button>");</script>
ResultLoading…
  • Line 15 prints which button gets focus.
  • Line 16 removes the toolbar. Line 17 puts it back. Line 18 adds a button.

It prints Focus: Green and Focus: Black, and the same after you put it back. Left Arrow from Green prints Focus: Herbal: the new button joined the row with tabindex -1. While the toolbar is off the page, it has none of the controllers' listeners, and its observer is off.

The listeners must be the very same functions, because of how removeEventListener() works (MDN, and removing listeners):

removeEventListener() needs the same functionPop out in the code editor (opens in a new tab)JavaScript
const kettle = new EventTarget();
kettle.addEventListener("boil", () => console.log("first"));
kettle.removeEventListener("boil", () => console.log("first"));

const second = () => console.log("second");
kettle.addEventListener("boil", second);
kettle.addEventListener("boil", second);
kettle.removeEventListener("boil", second);

kettle.dispatchEvent(new Event("boil"));
  • Line 3 tries to remove the first listener with a new arrow function. Same code, different function.
  • Lines 6 and 7 add one function twice. The browser keeps it once. Line 8 removes it.

It prints first only. Why it matters: a controller that makes a new arrow in hostConnected() can never take it off. Keep the function in a field, as lines 5 and 6 of RovingController do. Lesson 3.3 cleaned up the same way by hand.

Can you use reactive controllers without Lit?

Yes. A host is any object with four members (reactive-controller.ts):

  • addController() and removeController();
  • requestUpdate() and updateComplete.

Lit's docs say other libraries' base classes can be hosts too (Lit). ReactiveTea already has the last two (lesson 18.1). The kit adds the rest to TeaElement:

element.js: adding, removing, and the connection hooksJavaScript
  addController(controller) {
    this.#controllers.add(controller);
    if (this.#connected) controller.hostConnected?.();
  }

  removeController(controller) {
    this.#controllers.delete(controller);
  }

  connectedCallback() {
    for (const { name } of this.constructor.finalize().attributes.values()) {
      if (Object.hasOwn(this, name)) {
        throw new Error(`${this.localName}: the class field ${name} hides its generated property`);
      }
    }
    for (const [name, value] of this.#early) this[name] = value;
    this.#early.clear();
    this.requestUpdate();
    this.#connected = true;
    for (const controller of this.#controllers) controller.hostConnected?.();
  }

  disconnectedCallback() {
    this.#connected = false;
    for (const controller of this.#controllers) controller.hostDisconnected?.();
  }
  • Lines 1 to 4: addController() keeps the controller in a Set. One added while the element is connected starts at once, on line 3.
  • Lines 6 to 8: removeController() forgets it. It doesn't call hostDisconnected(), and neither does Lit's (lines 1085 to 1087).
  • Lines 18 to 20: connectedCallback() asks for the first update, marks the element connected, and starts each controller.
  • Lines 23 to 26: disconnectedCallback() stops each one.
element.js: update() calls the update hooks around render()JavaScript
  update(changed) {
    for (const controller of this.#controllers) controller.hostUpdate?.();
    const result = this.render(changed);
    if (result) renderInto(result, this.renderRoot);
    for (const controller of this.#controllers) controller.hostUpdated?.();
    this.updated(changed);
  }

  render(changed) {}

  updated(changed) {}
  • Line 2 calls hostUpdate() before drawing. Lines 3 and 4 draw.
  • Line 5 calls hostUpdated(). Line 6 calls the new updated() hook, on line 11.
Three rows. When it joins the page: connectedCallback, then an arrow to the shaded hostConnected(). In each update: the shaded hostUpdate(), then render(), then the shaded hostUpdated(), then updated(), joined by arrows. When it leaves the page: disconnectedCallback, then an arrow to the shaded hostDisconnected().When it joins the pageconnectedCallbackhostConnected()In each updatehostUpdate()render()hostUpdated()updated()When it leaves the pagedisconnectedCallbackhostDisconnected()
The shaded cards are the controller's hooks. TeaElement calls them at these points, and so does Lit: hostUpdate() before render(), and hostUpdated() before updated().

Why a #connected mark on line 3, and not isConnected? An element the parser made is already on the page in its constructor. A controller made in a class field would start twice. Lit checks for its render root instead, which its connectedCallback() makes (lines 1070 to 1079). Exercise 6 finds this bug.

Real-life analogyA standard wall socket

Asha's kettle came from one shop, and her toaster from another. Both plug into any wall socket built to the standard. The socket doesn't care who made the kettle.

In real life: The socket's standard shape
In JavaScript: The four host members
In real life: A kettle from any shop
In JavaScript: A controller written for Lit
In real life: The socket in the Leaf and Kettle wall
In JavaScript: TeaElement
In real life: Switching on
In JavaScript: hostConnected()

Now prove the points match. One controller prints each hook. Run it on each host, then press Remove the order:

Playground: one controller, two hosts
A traced order on TeaElement or LitElementPop out in the code editor (opens in a new tab)HTML
<tea-order>Sencha</tea-order><button id="remove">Remove the order</button><script type="module">  import "./tea-order.js";  document.querySelector("#remove").addEventListener("click", () => {    document.querySelector("tea-order").remove();  });</script>
ResultLoading…
Try it yourself
Our base class calls the hooks

TeaElement calls hostConnected() at the end of connectedCallback, hostUpdate() before render(), and hostUpdated() before updated(). Remove the order, and it calls hostDisconnected().

Only lines 1 and 4 of the tea-order.js tab change. The LitElement choice loads Lit 3.3.3.
  • In the trace-controller.js tab, line 4 adds the controller to its host. Lines 7 to 21 print each hook.
  • In the tea-order.js tab, line 5 makes the controller. Lines 11 to 22 print the host's own steps.

Both print the same six lines: controller: hostConnected, host: connectedCallback, controller: hostUpdate, host: render, controller: hostUpdated, and host: updated. Remove the order, and both print controller: hostDisconnected.

Lit's source has the same points. Its connectedCallback() calls hostConnected() last (lines 1137 to 1143). performUpdate() calls hostUpdate() before update() (line 1513). _$didUpdate() calls hostUpdated() before updated() (lines 1557 to 1580). Read each row across:

Where each host calls each hook
HookTeaElement calls itLit calls it
hostConnected()At the end of connectedCallback(), after asking for the first update.At the end of connectedCallback(), after making the render root.
hostUpdate()In update(), before render().In performUpdate(), after willUpdate() and before update().
hostUpdated()In update(), after render() and before updated().In _$didUpdate(), before firstUpdated() and updated().
hostDisconnected()In disconnectedCallback().In disconnectedCallback().

Why it matters: a controller written to those four members runs on either host. Lit Labs' MutationController runs on TeaElement unchanged.

How do you build behaviors from small pieces?

Controllers combine. A controller can make other controllers and hand them its host, as Lit's docs show with two clocks (Lit). This one gives a host's own child buttons one Tab stop:

button-group.js: a controller made of two controllersJavaScript
import { ChildrenController, RovingController } from "./tea-kit/controllers.js";

export class ButtonGroupController {
  constructor(host, options = {}) {
    this.children = new ChildrenController(host);
    this.roving = new RovingController(host, {
      ...options,
      items: () => [...host.children].filter((child) => child.localName === "button"),
    });
  }
}
  • Line 4 takes the host. The controller adds nothing to the host itself.
  • Line 5 makes a ChildrenController for the host. Lines 6 to 9 make a RovingController whose items are the host's child buttons.

The two smaller controllers add themselves to the host, so the host calls all their hooks. Libraries build them both ways. PatternFly's RovingTabindexController extends another controller (lines 15 to 17), and so does Spectrum's (lines 20 to 22). PatternFly's InternalsController.of() hands every caller the same controller for a host (lines 146 to 157). So the element's internals are attached once, as attachInternals() requires.

What is a behavioral element?

A behavioral element wraps markup the page already wrote, and adds a behavior to it. It draws nothing of its own. Thomas Wilburn calls them behavioral components: they enhance a chunk of the page instead of taking it over (his book). Lesson 5.6's HTML web components work this way.

tea-roving.js: an element that only hosts a controllerJavaScript
import { TeaElement } from "./tea-kit/element.js";
import { ButtonGroupController } from "./button-group.js";

class TeaRoving extends TeaElement {
  group = new ButtonGroupController(this);

  createRenderRoot() {
    return this;
  }
}

customElements.define("tea-roving", TeaRoving);
  • Line 5 is its only job: one ButtonGroupController.
  • Lines 7 to 9 draw in the element itself, and it draws nothing. Its children stay where the page put them.

Click Small and press Right Arrow, then End:

Three buttons, given arrow keys by tea-rovingPop out in the code editor (opens in a new tab)HTML
<tea-roving role="toolbar" aria-label="Cup size">  <button>Small</button>  <button>Medium</button>  <button>Large</button></tea-roving><script type="module">  import "./tea-roving.js";  const sizes = document.querySelector("tea-roving");  sizes.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>
ResultLoading…
  • Line 1: the page gives the group its role and its name. Lines 2 to 4 are ordinary buttons.
  • Line 9 prints each focus.

It prints Focus: Small, Focus: Medium, then Focus: Large. Before the script runs, they're three plain buttons, each its own Tab stop. If the script never loads, nothing breaks.

Real-life analogyA turntable on the table

Leaf and Kettle puts a turntable in the middle of its big tables. Any dish on it can turn to each guest. The dishes don't change. Take the turntable away, and the dishes are still on the table.

In real life: The turntable
In JavaScript: tea-roving
In real life: The dishes on it
In JavaScript: The page's own buttons
In real life: Turning a dish to a guest
In JavaScript: The arrow keys
In real life: Dishes on the table with no turntable
In JavaScript: Buttons that work with no script

Should you use a mixin, a controller, or a base class?

Lit's composition overview gives a rule. A component is its mixin, and has its controller. Pick a controller, unless the feature needs one of two things (Lit):

  • it adds public API to the component;
  • it needs very fine access to the component's lifecycle.

The cup's form mixin needs both: it adds form, and it replaces requestUpdate(). The toolbar's keys need neither, so they're controllers. What every component needs stays in the base class, as lesson 19.1 said. Read each row across:

Four ways to share behavior
QuestionBase classMixinControllerBehavioral element
How does a component get it?It extends it: extends TeaElement.It wraps its parent: extends FormAssociated(TeaElement).It makes one: new RovingController(this, …).The page wraps markup in it: <tea-roving>.
Does it add to the component's API?Yes. Everything it has is the component's.Yes. Its members join the component's.No. It's a separate object, unless the component hands it out.No. It has an API of its own.
How many can one component use?One. A class has one parent.Several, stacked in order.Several, even two of the same kind.Any number, around any markup.
What goes wrong most often?The chain grows tall, and a change reaches every child.A hook forgets super, or the same mixin comes twice.Something it starts never stops.The markup inside isn't what it expects.
Where is it in the kit?TeaElement and TeaFormControl.FormAssociated.ChildrenController and RovingController.This lesson's tea-roving.
Which pattern fits?
  • Styles, a template, and render() for every component in the kit
  • A form property and a value the form sends, on a cup that already has a parent
  • Hand the form the value inside requestUpdate(), before a change returns
  • Arrow keys between a component's buttons, in any component
  • Two separate timers on one tea card
  • Arrow keys for buttons the server already wrote into the page
Try it yourself
0 of 6 correct

Sort each feature by the pattern it fits best.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Adding a mixin and two controllers to the tea kit

This version of the kit is kitAfter193. Two files are new, and four change:

  • tea-kit/element.js: TeaElement is a controller host, with a new updated() hook.
  • tea-kit/form-associated.js, new: the FormAssociated mixin.
  • tea-kit/controllers.js, new: ChildrenController and RovingController.
  • tea-kit/tea-cup.js: the cup is a form control now. It looks the same.
  • tea-kit/tea-flavors.js: the toolbar is built from the two controllers. Its keys, role, and name stay the same.
  • tea-kit/custom-elements.json: the new members, the cup's mixin, and the two new modules.

Here they work together on an order form. Click Light, press Right Arrow, then Enter. Then press Tab to reach Order, and press Enter:

An order form with the kit's toolbar and cupPop out in the code editor (opens in a new tab)HTML
<form>  <tea-flavors label="Roast">    <button type="button">Light</button>    <button type="button">Dark</button>  </tea-flavors>  <p><tea-cup name="cup" size="4">Hojicha</tea-cup></p>  <button>Order</button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("form");  form.querySelector("tea-flavors").addEventListener("click", (event) => {    const roast = event.target.closest("button")?.textContent;    if (roast) form.querySelector("tea-cup").roast = roast;  });  form.addEventListener("submit", (event) => {    event.preventDefault();    console.log("Order:", new FormData(form).get("cup"));  });</script>
ResultLoading…
  • Line 2 is the toolbar, named Roast. Line 6 is the cup.
  • Lines 12 to 15 set the cup's roast from the button pressed.
  • Lines 16 to 19 print the order, instead of sending it.

It prints Order: 4 dark. In Chrome's accessibility tree, the row is still a toolbar named Roast, with its two buttons. The JSDoc and the manifest document the mixin, both controllers, and the cup's new name and disabled.

Common mix-ups

  • "A mixin that skips super shows an error." No. Nothing throws. The playground's note stayed blank, and the console stayed empty.
  • "The order of mixins doesn't matter." No. The outer mixin's code before super runs first, and its code after super runs last.
  • "Applying a mixin twice does nothing." No. Its code runs twice: two notes counted to 4. dedupe() stops it.
  • "Controllers only work with Lit." No. Any host with the four members runs them. TeaElement printed the same trace as LitElement.
  • "removeController() stops a controller." No. It only forgets it. Stop the controller first.
  • "Removing a listener with the same code takes it off." No. It needs the very same function. Keep it in a field.
  • "A controller's methods become the component's." No. It's a separate object. Users of the component can't reach it unless the component hands it out.

Practice exercises

Exercise 1 · Warm-upPredict two add-ins

Two mixins add a word to the tea. Predict what the code prints, then run it.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const Add = (word) => (Base) =>
  class extends Base {
    brew() {
      return `${super.brew()} + ${word}`;
    }
  };

class Tea {
  brew() {
    return "tea";
  }
}

class Chai extends Add("milk")(Add("ginger")(Tea)) {}
console.log(new Chai().brew());

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upPredict what removeController() leaves

    The order uses the trace controller from the playground. The button removes the controller, then the order. What does the page print when you press it?

    <tea-order>Sencha</tea-order><button id="stop">Stop tracing, then remove</button><script type="module">  import "./tea-order.js";  const order = document.querySelector("tea-order");  document.querySelector("#stop").addEventListener("click", () => {    order.removeController(order.trace);    order.remove();    console.log("Removed");  });</script>
    ResultLoading…

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFind the missing super

      A Noted mixin prints a cup's note. But the cup shows the wrong size, and Bigger does nothing. Fix the noted-cup.js tab. What does the cup show after one press of Bigger?

      <p><noted-cup size="4" roast="dark" note="no sugar">Hojicha</noted-cup></p><button id="bigger">Bigger</button><script type="module">  import "./noted-cup.js";  const cup = document.querySelector("noted-cup");  document.querySelector("#bigger").addEventListener("click", () => cup.setAttribute("size", "5"));</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeMake the badge a form control

        The kit's badge already has a parent, TeaElement. The mixin goes on top. Write formValue() so the form sends the number of cups. What does the page print?

        <form>  <tea-cups name="cups">3 cups</tea-cups></form><script type="module">  import { FormAssociated } from "./tea-kit/form-associated.js";  import { TeaBadge } from "./tea-kit/tea-badge.js";  class TeaCups extends FormAssociated(TeaBadge) {    formValue() {      return null;    }  }  customElements.define("tea-cups", TeaCups);  console.log("Sent:", new URLSearchParams(new FormData(document.forms[0])).toString());</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeStop a page-wide shortcut

          A ShortcutController listens on the whole document. Press / to jump to the finder's box. Make it stop when the finder leaves the page. What does the second / print?

          <tea-finder></tea-finder><button id="remove">Remove the finder</button><script type="module">  import { TeaElement } from "./tea-kit/element.js";  import { ShortcutController } from "./shortcut-controller.js";  class TeaFinder extends TeaElement {    static template = `<input aria-label="Find a tea">`;    shortcut = new ShortcutController(this, "/", (event) => {      event.preventDefault();      this.renderRoot.querySelector("input").focus();      console.log("Shortcut. On the page:", this.isConnected);    });  }  customElements.define("tea-finder", TeaFinder);  document.querySelector("#remove").onclick = () => document.querySelector("tea-finder").remove();</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeFind why hostConnected runs twice

            A tiny host on HTMLElement starts its controllers. The page prints controller: hostConnected twice. Fix the tiny-host.js tab. How many times does it print after your fix?

            <tea-order>Sencha</tea-order><script type="module">  import { TinyHost } from "./tiny-host.js";  import { TraceController } from "./trace-controller.js";  class TeaOrder extends TinyHost {    trace = new TraceController(this);  }  customElements.define("tea-order", TeaOrder);</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The mixins and controllers quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does a mixin like (Base) => class extends Base {} give back?

                Choose an answer to see the explanation.

              2. Question 2 of 7In class TeaNote extends Focusable(Counted(TeaElement)), Focusable's connectedCallback forgets super.connectedCallback(). What happens?

                Choose an answer to see the explanation.

              3. Question 3 of 7What does this code print, line by line?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const Warmed = (Base) =>
                  class extends Base {
                    brew() {
                      console.log("warm the pot");
                      super.brew();
                    }
                  };
                const Strained = (Base) =>
                  class extends Base {
                    brew() {
                      super.brew();
                      console.log("strain the leaves");
                    }
                  };
                class Tea {
                  brew() {
                    console.log("steep");
                  }
                }
                class Sencha extends Strained(Warmed(Tea)) {}
                new Sencha().brew();

                Choose an answer to see the explanation.

              4. Question 4 of 7When does TeaElement call a controller's hostUpdated()?

                Choose an answer to see the explanation.

              5. Question 5 of 7A host calls removeController(trace), then leaves the page. Does the controller hear hostDisconnected()?

                Choose an answer to see the explanation.

              6. Question 6 of 7Why does RovingController keep its listeners in fields, like #onKeydown = (event) => …?

                Choose an answer to see the explanation.

              7. Question 7 of 7A feature must add a public form property to the cup. Lit's composition overview points to which pattern?

                Choose an answer to see the explanation.

              Key takeaways

              • A mixin is a function that takes a class and returns a subclass of it.
              • Every hook a mixin replaces calls super. One that forgets breaks the classes below it, silently.
              • The outer mixin runs first before super, and last after it. dedupe() keeps a mixin to one copy.
              • FormAssociated makes any TeaElement class a form control, and hands the form each change at once.
              • A controller is an object the component owns. It starts in hostConnected() and stops in hostDisconnected().
              • TeaElement calls the four hooks at the same points as Lit, so Lit controllers run on it.
              • Controllers combine into bigger ones. A behavioral element hosts one around the page's own markup.
              • Pick a controller, unless the feature adds public API or needs a fine lifecycle hook.

              Remember the one-liner.
              Blend in a mixin when the component must be more; clip on a controller when it must have more.

              Sources

              The facts on this page come from these docs, posts, and source files:

              Support data comes from MDN's browser-compat-data.

              Coming next: Context and dependency injection. Let a component get data or services from an ancestor without passing it through every level.

              CompleteFrontend Clear concepts. Working examples.