Alpine.js Bowling Alley

Demonstrating $el, $refs, and $root

Alley Status Log

Log is empty. Interact with the demos below.

$el: The Current Lane

Refers to the element the event handler is on. Like a bowler interacting directly with their own lane.

Lanes:

Lane 1

Lane 2

Lane 3

Code Example

<!-- The button references itself with $el -->
<button @click="waxLane($el)">Wax This Lane</button>

<!-- In Alpine.data -->
waxLane(el) {
  const lane = el.closest('.lane');
  lane.classList.add('bg-yellow-200', 'border-yellow-400');
  // ...
}

$refs: Named Equipment

Access any element with x-ref from anywhere in the component. Like the front desk controlling specific equipment by name.

Front Desk Control Panel:

Pinsetter is idle.
Ball return is waiting.

Code Example

<!-- Any element can be named with x-ref -->
<div x-ref="pinsetterRef">...</div>

<!-- In Alpine.data -->
activatePinsetter() {
  this.$refs.pinsetterRef.innerText = 'Resetting pins...';
  this.$refs.pinsetterRef.classList.add('bg-green-300');
  // ...
}

$root: The Entire Alley

Refers to the root element of the component. Like the manager changing the mode for the entire alley.

Alley-Wide Controls:

Code Example

The $root is this entire demo's container.

<!-- The root component element -->
<div x-data="bowlingAlley">...</div>

<!-- In Alpine.data -->
startCosmicBowling() {
  this.$root.classList.add('bg-gray-900', 'border-purple-500');
  this.$root.querySelectorAll('h1, h2, h3, h4, p').forEach(el => {
    el.classList.add('text-white');
  });
  // ...
}