Skip to content

Commit

Permalink
Add better entanglement infinite-loop protection
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio committed Jan 23, 2024
1 parent 26281b7 commit 8001383
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions packages/alpinejs/src/entangle.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,30 @@ import { effect, release } from './reactivity'
export function entangle({ get: outerGet, set: outerSet }, { get: innerGet, set: innerSet }) {
let firstRun = true
let outerHash
let innerHash

let reference = effect(() => {
const outer = outerGet()
const inner = innerGet()

if (firstRun) {
innerSet(cloneIfObject(outer))
firstRun = false
outerHash = JSON.stringify(outer)
} else {
const outerHashLatest = JSON.stringify(outer)
const innerHashLatest = JSON.stringify(inner)

if (outerHashLatest !== outerHash) { // If outer changed...
innerSet(cloneIfObject(outer))
outerHash = outerHashLatest
} else { // If inner changed...
} else if (outerHashLatest !== innerHashLatest) { // If inner changed...
outerSet(cloneIfObject(inner))
outerHash = JSON.stringify(inner)
} else { // If nothing changed...
// Prevent an infinite loop...
}
}
JSON.stringify(innerGet())
JSON.stringify(outerGet())

outerHash = JSON.stringify(outerGet())
innerHash = JSON.stringify(innerGet())
})

return () => {
Expand Down

0 comments on commit 8001383

Please sign in to comment.