AI Workshop: learn to build apps with AI →
Alpine.js: Watching variables change

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


You can watch/listen for changes in an Alpine data variable, and run a function when a change happens.

You do so using $watch() inside the x-init attribute, which runs when Alpine initializes the component.

For example I have some HTML that belongs to a modal, and any time this modal is opened I want to clear the name data, so the input field is always empty:

<div
  x-data="{ name: '' }"
  x-init="$watch('showModal', () => { name = '' })">
  <form>
    <input name="name" x-model="name" />
  </form>
</div>

Lessons in this unit:

0: Introduction
1: Installing Alpine
2: The basics of Alpine
3: Events
4: Defining data
5: Looping
6: Binding user input to variables
7: ▶︎ Watching variables change
8: Stores