Skip to content

Commit

Permalink
Magics/$mixin: Fix getters and setters not being persisted
Browse files Browse the repository at this point in the history
  • Loading branch information
ryangjchandler committed May 8, 2024
1 parent c4cdd6c commit 3dcb010
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 16 deletions.
31 changes: 15 additions & 16 deletions packages/alpinejs/src/magics/$mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,22 @@ magic('mixin', () => (...datas) => {
let inits = []
let destroys = []

const mixed = datas.reduce((acc, data) => {
const mixed = {
init() {
inits.forEach(init => init.call(this))
},
destroy() {
destroys.forEach(destroy => destroy.call(this))
},
};

for (let data of datas) {
if (typeof data === 'function') {
data = data()
}

if (typeof data !== 'object') continue

if (typeof data.init === 'function') {
inits.push(data.init)
}
Expand All @@ -17,20 +28,8 @@ magic('mixin', () => (...datas) => {
destroys.push(data.destroy)
}

if (typeof data === 'object') {
return { ...acc, ...data }
}

return acc
}, {})

return {
...mixed,
init() {
inits.forEach(init => init.call(this))
},
destroy() {
destroys.forEach(destroy => destroy.call(this))
}
Object.defineProperties(mixed, Object.getOwnPropertyDescriptors(data))
}

return mixed
})
25 changes: 25 additions & 0 deletions tests/cypress/integration/magics/$mixin.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,28 @@ test(
get("#2").should(haveText("bar"));
}
);

test(
'$mixin maintains getters and setters',
html`
<div x-data="$mixin(
{
get foo() {
return 'bar'
}
},
{
get baz() {
return 'qux'
}
}
)">
<span id="1" x-text="foo"></span>
<span id="2" x-text="baz"></span>
</div>
`,
({ get }) => {
get('#1').should(haveText('bar'))
get('#2').should(haveText('qux'))
},
)

0 comments on commit 3dcb010

Please sign in to comment.