Skip to content

Instantly share code, notes, and snippets.

@KevinBatdorf
Last active January 22, 2021 19:11
Show Gist options
  • Save KevinBatdorf/e8b18ccb20463bc4297747e8a8bac7f2 to your computer and use it in GitHub Desktop.
Save KevinBatdorf/e8b18ccb20463bc4297747e8a8bac7f2 to your computer and use it in GitHub Desktop.
AlpineJS Magic Helper to use x-init on child elements
// Demo; https://codepen.io/KevinBatdorf/pen/RwGEdpr?editors=1011
// Load in before you load Alpine
function AlpineAutoInitChildren() {
// Use: <div x-data x-init="$initChildren()">
Alpine.addMagicProperty('initChildren', ($el) => {
return () => {
// Grab all child x-init. Customize if you want to only run based on a specific condition
Array.from($el.querySelectorAll('[x-init]')).forEach(child => {
// No $nextTick and we need to wait a tick to have access to $el.__x
setTimeout(() => {
// Modified version of what Alpine uses
// https://github.com/alpinejs/alpine/blob/master/src/utils.js#L87
// Customize the selector you have nested components you need to ignore, etc
new Function(
'$data',
`var __alpine_result
with($data) {
__alpine_result = ${child.getAttribute('x-init')}
}
return __alpine_result`
)($el.__x.$data)
}, 0)
})
}
})
}
// This ensures that Alpine is initialized AFTER our script is evaluated/loaded
const alpine = window.deferLoadingAlpine || ((alpine) => alpine())
window.deferLoadingAlpine = (callback) => {
AlpineAutoInitChildren()
alpine(callback)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment