Alpine.js Smart Home

Demonstrating $el, $refs, and $root

$el: The Current Device

Analogy: You're tapping a smart bulb directly. $el refers to the element you are interacting with.

Code Example:


<button @click="toggleLight()">...</button>

// In Alpine.data component:
toggleLight() {
    this.lightIsOn = !this.lightIsOn;
    
    // Use $el for a one-off effect
    this.$el.classList.add('animate-pulse-once');
    setTimeout(() => this.$el.classList.remove('animate-pulse-once'), 500);

    Alpine.store('systemLog').log('$el: Toggled smart bulb directly.');
}
                                    

$refs: Named Appliances

Analogy: Using a central remote to control specific appliances by name, like the "Living Room TV".

Control Panel

Kitchen Thermostat

📺 Living Room TV

Status: OFF

🌡️ Kitchen Thermostat

Set to:

Code Example:


<div x-ref="livingRoomTV">...</div>
<button @click="operateTV()">...</button>

// In Alpine.data component:
operateTV() {
    // ... update state ...
    this.$refs.livingRoomTV.classList.add('bg-blue-100');
    this.$refs.tvStatus.textContent = 'Status: ON';
    Alpine.store('systemLog').log('$refs: Used remote for TV.');
}
                                    

$root: The Entire House

Analogy: Activating a scene like "Goodnight" which affects the entire house component from a single button.

Current House Mode:

Code Example:


<div x-data="smartHomeSystem">
    <!-- Deeply nested button -->
    <button @click="setHouseMode('night')">...</button>
</div>

// In Alpine.data component:
setHouseMode(mode) {
    this.houseMode = mode;
    // $root refers to the top-level div[x-data]
    if (mode === 'night') {
        this.$root.classList.add('dark');
        Alpine.store('systemLog').log('$root: Whole house set to night.');
    } else {
        this.$root.classList.remove('dark');
        Alpine.store('systemLog').log('$root: Whole house set to day.');
    }
}
                                    

System Activity Log

Perform an action to see the log...

Concept Comparison

  • $el
    The Current Device

    Refers to the DOM element the Alpine directive is on. Useful for one-off, direct manipulations from an event handler.

  • $refs
    Named Appliances

    Accesses other DOM elements within the same component that have an x-ref attribute. Perfect for a "controller" to manipulate specific "parts".

  • $root
    The Entire House

    Refers to the root DOM element of the current Alpine component. Ideal for broad actions that affect the whole component boundary, regardless of how deeply nested the trigger is.