Sometimes we want to debounce the updating of bound input. This is useful for things like real-time search inputs that fetch new data from the server every time the search property changes.
Version
Alpine 3.9
x-model.debounce
We can use x-model
to realize two-way data binding with debouncing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body x-data="{ search: '' }">
<input type="text" x-model.debounce="search" />
<span x-text="search" />
</body>
</html>
Line 9
<body x-data="{ search: '' }">
<input type="text" x-model.debounce="search" />
<span x-text="search" />
</body>
x-model.debounce
: two-way data binding the input value to a variable with debounce. The default debounce time is250
msx-text
: display the value of a variable
x-model.debounce.500ms
We can specify debounce time as a time modifier.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body x-data="{ search: '' }">
<input type="text" x-model.debounce.500ms="search" />
<span x-text="search" />
</body>
</html>
Line 9
<body x-data="{ search: '' }">
<input type="text" x-model.debounce.500ms="search" />
<span x-text="search" />
</body>
x-model.debounce.500ms
: specify250
ms as debounce time
Autocomplete
x-model
with debounce
is useful for autocomplete.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<script src="https://cdn.tailwindcss.com"></script>
<title>Alpine</title>
</head>
<body x-data="{ search: '', items: ['iPhone', 'Macbook', 'Switch'] }">
<div>
<input
x-model.debounce.500ms="search"
class="w-52 border border-gray-200 px-2"
/>
</div>
<ul x-show="search" class="mt-2 w-52">
<template x-for="x in items.filter(x => x.startsWith(search))">
<li x-text="x" class="px-2" />
</template>
</ul>
</body>
</html>
Line 10
<body x-data="{ search: '', items: ['iPhone', 'Macbook', 'Switch'] }">
search
: variable to hold user inputitems
: all data for search
Line 12
<input
x-model.debounce.500ms="search"
class="w-52 border border-gray-200 px-2"
/>
x-model.debounce.500ms
: two way binding for user input with debounce time500
ms
Line 17
<ul x-show="search" class="mt-2 w-52">
x-show
:<ul>
is hidden whensearch
is empty
Line 18
<template x-for="x in items.filter(x => x.startsWith(search))">
<li x-text="x" class="px-2" />
</template>
x-for
: filter dynamically by user’s inputx-text
: display the filtered result
Conclusion
- We can debounce the input without any external library, just adding
debounce
modifier tox-model