how to dispatch param using x-init in Alpinejs
The reason of this behavior is that you dispatch the myparams
event before the initialization of listener for myparams
event. So the first time no one is listening.
The future-proof solution is to use $nextTick
so the dispatch fires after DOM updates.
<div x-data="initMyparams"></div>
<section x-data="mypage" @myparams.window="title = $event.detail.title">
<h2 x-text="title"></h2>
</section>
Where we have a new initMyparams
component using $nextTick
:
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('mypage', () => ({
title: '',
init() {
console.log('I will get evaluated when initializing this component.')
},
})),
Alpine.data('initMyparams', () => ({
init() {
this.$nextTick(() => this.$dispatch('myparams', { title: 'Initialised' }))
},
}))
})
</script>