Alpine.js Science Museum

Exploring $el, $refs, and $root

The Analogy

$el: The Current Exhibit

An element modifying itself.

This button represents an interactive exhibit. Clicking it will make it "light up" by changing its own styles and text using $el.

Code Snippet:

// In Alpine.data('exhibit')
interact() {
  const button = this.$el.querySelector('button');
  // ...change button's class and text
  this.$dispatch('log', 'Exhibit ($el) was activated.');
}

$refs: Named Displays

One element controlling other named elements.

From the curator's desk, we can spotlight specific named displays (x-ref) around the room using $refs.

Curator's Control Panel

T-Rex Skeleton

Planetarium Dome

Code Snippet:

// In Alpine.data('curatorDesk')
spotlight(refName) {
  this.$refs[refName].classList.add('ring-4');
  // ...
  this.$dispatch('log', `Used $refs for '${refName}'.`);
}

$root: The Entire Museum

A nested element affecting its component's root.

An event coordinator inside the museum needs to announce closing time. This action, triggered from a nested component, affects the entire museum (the component's root element with x-data="museum") using $root.

Coordinator's Booth

Code Snippet:

// In Alpine.data('eventCoordinator')
announceClosing() {
  this.$root.classList.add('bg-slate-800');
  // ...
  this.$dispatch('log', 'Used $root for closing.');
}

Museum Status Log

No events recorded yet. Interact with the demos above.