diff --git a/packages/alpinejs/src/magics/$id.js b/packages/alpinejs/src/magics/$id.js index 28a887df7..40f2f8a54 100644 --- a/packages/alpinejs/src/magics/$id.js +++ b/packages/alpinejs/src/magics/$id.js @@ -2,10 +2,8 @@ import { magic } from '../magics' import { closestIdRoot, findAndIncrementId } from '../ids' import { interceptClone } from '../clone' -magic('id', (el, { cleanup }) => (name, key = null) => { - let cacheKey = `${name}${key ? `-${key}` : ''}` - - return cacheIdByNameOnElement(el, cacheKey, cleanup, () => { +magic('id', (el, { cleanup }) => (name, key = null, cache = true) => { + const getId = () => { let root = closestIdRoot(el, name) let id = root @@ -15,7 +13,15 @@ magic('id', (el, { cleanup }) => (name, key = null) => { return key ? `${name}-${id}-${key}` : `${name}-${id}` - }) + } + + if (cache) { + let cacheKey = `${name}${key ? `-${key}` : ''}` + + return cacheIdByNameOnElement(el, cacheKey, cleanup, getId) + } else { + return getId() + } }) interceptClone((from, to) => { diff --git a/tests/cypress/integration/magics/$id.spec.js b/tests/cypress/integration/magics/$id.spec.js index 61296fac3..6061962a7 100644 --- a/tests/cypress/integration/magics/$id.spec.js +++ b/tests/cypress/integration/magics/$id.spec.js @@ -26,6 +26,47 @@ test('$id generates a unique id', } ) +test('$id can be forced to generate unique ids', + html` +
+

+ + +
+ +
+

+ + +
+ +
+

+ + +
+ `, + ({ get }) => { + get('#1 h1').should(haveText('initial')) + get('#1 button').click() + get('#1 h1').should(haveText('initial, cached-1')) + get('#1 button').click() + get('#1 h1').should(haveText('initial, cached-1, cached-1')) + + get('#2 h1').should(haveText('initial')) + get('#2 button').click() + get('#2 h1').should(haveText('initial, not-cached-1')) + get('#2 button').click() + get('#2 h1').should(haveText('initial, not-cached-1, not-cached-2')) + + get('#3 h1').should(haveText('initial')) + get('#3 button').click() + get('#3 h1').should(haveText('initial, not-cached-with-key-1-key')) + get('#3 button').click() + get('#3 h1').should(haveText('initial, not-cached-with-key-1-key, not-cached-with-key-2-key')) + } +) + test('$id works with keys and nested data scopes', html`