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’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework mutation observer #3929

Merged
merged 1 commit into from
Dec 15, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 13 additions & 16 deletions packages/alpinejs/src/mutation.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,27 +65,24 @@ export function stopObservingMutations() {
currentlyObserving = false
}

let recordQueue = []
let willProcessRecordQueue = false
let queuedMutations = []

export function flushObserver() {
recordQueue = recordQueue.concat(observer.takeRecords())
let records = observer.takeRecords()

if (recordQueue.length && ! willProcessRecordQueue) {
willProcessRecordQueue = true
queuedMutations.push(() => records.length > 0 && onMutate(records))

queueMicrotask(() => {
processRecordQueue()
let queueLengthWhenTriggered = queuedMutations.length

willProcessRecordQueue = false
})
}
}

function processRecordQueue() {
onMutate(recordQueue)

recordQueue.length = 0
queueMicrotask(() => {
// If these two lengths match, then we KNOW that this is the LAST
// flush in the current event loop. This way, we can process
// all mutations in one batch at the end of everything...
if (queuedMutations.length === queueLengthWhenTriggered) {
// Now Alpine can process all the mutations...
while (queuedMutations.length > 0) queuedMutations.shift()()
}
})
}

export function mutateDom(callback) {
Expand Down