Skip to content
Closed
Show file tree
Hide file tree
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
16 changes: 11 additions & 5 deletions packages/alpinejs/src/magics/$id.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) => {
Expand Down
41 changes: 41 additions & 0 deletions tests/cypress/integration/magics/$id.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,47 @@ test('$id generates a unique id',
}
)

test('$id can be forced to generate unique ids',
html`
<div x-data="{ heading: 'initial' }" id="1">
<h1 x-text="heading"></h1>

<button x-on:click="heading += ', ' + $id('cached')"></button>
</div>

<div x-data="{ heading: 'initial' }" id="2">
<h1 x-text="heading"></h1>

<button x-on:click="heading += ', ' + $id('not-cached', null, false)"></button>
</div>

<div x-data="{ heading: 'initial' }" id="3">
<h1 x-text="heading"></h1>

<button x-on:click="heading += ', ' + $id('not-cached-with-key', 'key', false)"></button>
</div>
`,
({ 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`
<div x-data x-id="['foo']" id="1">
Expand Down