Understanding `$el`, `$refs`, and `$root`
A musician can act on themselves. `$el` refers to the DOM element the Alpine directive is on. The action is self-contained.
Ready to play...
Code Example:
<button @click="takeSpotlight($el)">...</button>
// In Alpine.data component:
takeSpotlight(el) {
// 'el' is the button element itself
const musician = el.closest('[x-ref=musicianEl]');
// ... manipulate musician element ...
}
The conductor can call out a specific, named instrument. `$refs` lets you access a named element from anywhere within the component.
Conductor's Commands:
Code Example:
<div x-ref="piano">...</div>
<button @click="spotlightInstrument('piano')">
// In Alpine.data component:
spotlightInstrument(name) {
const instrument = this.$refs[name];
// ... manipulate instrument element ...
}
The conductor can give a command to everyone. `$root` refers to the top-level element of the entire component (`x-data`).
Stage Controls
(Affects this entire white card)
Code Example:
<div x-data="concertHall">
<button @click="startIntermission()">...</button>
</div>
// In Alpine.data component:
startIntermission() {
const orchestra = this.$root;
// ... manipulate orchestra element ...
}