Skip to content

Commit

Permalink
fix: memoization when injecting magic (#4276)
Browse files Browse the repository at this point in the history
* fix: memoization when injecting magic

* extract get utlilties to a function

* add return comment

* fix tests

* refactor

* wip

---------

Co-authored-by: Caleb Porzio <[email protected]>
  • Loading branch information
AbhiShake1 and calebporzio authored Jul 1, 2024
1 parent 4c3478c commit ac63592
Showing 1 changed file with 13 additions and 15 deletions.
28 changes: 13 additions & 15 deletions packages/alpinejs/src/magics.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,28 +9,26 @@ export function magic(name, callback) {
}

export function injectMagics(obj, el) {
Object.entries(magics).forEach(([name, callback]) => {
let memoizedUtilities = null;
function getUtilities() {
if (memoizedUtilities) {
return memoizedUtilities;
} else {
let [utilities, cleanup] = getElementBoundUtilities(el)

memoizedUtilities = {interceptor, ...utilities}

onElRemoved(el, cleanup)
return memoizedUtilities;
}
}
let memoizedUtilities = getUtilities(el)

Object.entries(magics).forEach(([name, callback]) => {
Object.defineProperty(obj, `$${name}`, {
get() {
return callback(el, getUtilities());
return callback(el, memoizedUtilities);
},
enumerable: false,
})
})

return obj
}

export function getUtilities(el) {
let [utilities, cleanup] = getElementBoundUtilities(el)

let utils = { interceptor, ...utilities }

onElRemoved(el, cleanup)

return utils;
}

0 comments on commit ac63592

Please sign in to comment.