Alpine.js on Campus

Exploring $el, $refs, and $root with a University Analogy.

Campus Action Log

$el

Analogy: The Current Building

$el refers to the DOM element an event listener is attached to. It's like standing inside a building and referring to "this building".

Science Hall

Example Code:
<button @click="toggleSecurity($el)">
toggleSecurity(el) {
  const building = el.closest('.building');
  building.classList.toggle('active');
}

$refs

Analogy: Named Facilities

$refs gives you direct access to elements marked with x-ref. It's a central directory to control specific, named locations on campus from anywhere.

Library
Gymnasium

Campus Control Panel

Example Code:
<div x-ref="library">...</div>
<button @click="toggleFacility('library')">
toggleFacility(name) {
  const facility = this.$refs[name];
  facility.classList.toggle('closed');
}

$root

Analogy: The Entire Campus

$root refers to the root element of an Alpine component (the one with x-data). It's for campus-wide announcements that affect the entire area.

Campus Administration

A campus-wide event is active!

Look Around! Clicking the button adds a yellow glow to the entire demo container, as it is the component's $root.

Example Code:
<div x-data="myComponent"> <!-- $root -->
  <button @click="this.$root.classList.toggle('active')">
</div>