Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Promise to $nextTick #2841

Merged
merged 1 commit into from Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions packages/alpinejs/src/nextTick.js
Expand Up @@ -3,14 +3,19 @@ let tickStack = []

let isHolding = false

export function nextTick(callback) {
tickStack.push(callback)

queueMicrotask(() => {
isHolding || setTimeout(() => {
releaseNextTicks()
})
export function nextTick(callback = () => {}) {
queueMicrotask(() => {
isHolding || setTimeout(() => {
releaseNextTicks()
})
})

return new Promise((res) => {
tickStack.push(() => {
callback();
res();
});
})
}

export function releaseNextTicks() {
Expand Down
19 changes: 19 additions & 0 deletions packages/docs/src/en/magics/nextTick.md
Expand Up @@ -21,3 +21,22 @@ title: nextTick
```

In the above example, rather than logging "Hello" to the console, "Hello World!" will be logged because `$nextTick` was used to wait until Alpine was finished updating the DOM.

<a name="promises"></a>

## Promises

`$nextTick` returns a promise, allowing the use of `$nextTick` to pause an async function until after pending dom updates. When used like this, `$nextTick` also does not require an argument to be passed.

```alpine
<div x-data="{ title: 'Hello' }">
<button
@click="
title = 'Hello World!';
await $nextTick();
console.log($el.innerText);
"
x-text="title"
></button>
</div>
```