Alpine.js on the Theater Stage

Understanding $el, $refs, and $root through a theatrical analogy.

$el

Analogy: The Current Actor

$el refers to the DOM element the Alpine directive is on. It's like an actor performing an action on themself, like changing their own pose or speaking a line.

Actor's Actions

// In the component's method:

takeSpotlight() {
  this.$el.classList.add(...);
  this.$el.innerText = '...';
}

$refs

Analogy: The Named Props

$refs lets you access other DOM elements by a name you give them with x-ref. It's like a stage manager using a control panel to interact with specific props like the "spotlight" or "backdrop".

The Stage

A mysterious monolith

// In the component's method:

toggleSpotlight() {
  this.$refs.spotlight.classList.toggle(...);
}

$root

Analogy: The Entire Production

$root refers to the root element of the entire Alpine component. It's like a director giving a command that affects the whole show, no matter how deeply nested the director is.

Director's Controls

These buttons are inside this card, but they control the entire page component.

// On an element inside the component:

<button @click="$root.toggleIntermission()">
  ...
</button>

Production Log

No actions logged yet. Interact with the demos above.