Alpine.js Cockpit Simulator

Understanding $el, $refs, and $root

$el : The Current Display

$el refers to the current DOM element. It's like a single display in the cockpit that can change its own state (e.g., its text or color) when you interact with it directly.

Simulator: System Check Button

Code Snippet

<button
  @click="checkSystem($el)">
  ...
</button>

// Script
checkSystem(element) {
  element.textContent = 'System OK';
  element.classList.add('bg-green-600');
  element.disabled = true;
}

$refs : Named Controls

$refs provides access to other elements within the same component, identified by a name (x-ref). It's like a central control panel that can operate specific, named systems elsewhere in the cockpit.

Simulator: Control & Indicator Panel

Controls

Indicators

Landing Gear RETRACTED
Autopilot OFF

Code Snippet

<button @click="toggleLandingGear()">...</button>
<div x-ref="landingGearIndicator">...</div>

// Script
toggleLandingGear() {
  let indicator = this.$refs.landingGearIndicator;
  // ... logic to update indicator ...
}

$root : The Entire Cockpit

$root refers to the top-most DOM element of the current component. It's like an emergency system that affects the entire cockpit, regardless of where the trigger is located inside.

Simulator: Emergency Alert System

This button is nested deep, but can affect the whole component.

Code Snippet

<div x-data="rootDemo"
  :class="{ 'emergency-mode': inEmergency }">
  <!-- Nested Deep Inside -->
  <button @click="triggerEmergency()">
    ...
  </button>
</div>

// Script
triggerEmergency() {
  this.inEmergency = true;
  // $root could also be used directly:
  // this.$root.classList.add(...)
}

System Log

Awaiting pilot input...