shez1983's avatar

listening to dynamic livewire events from Javascript

so I can get this to work:

$this->dispatch("post-updated.{$post->id}");

and listen from component

#[On('post-updated.{post.id}')] 

but having diffculty trying to access it from global js

document.addEventListener('livewire:init', () => {
        Livewire.on(post-updated', ({ postId }) => {
            alert(14);
            console.log(14);
            // ...
        });

        Livewire.on('post-updated', postId => {
            alert(12);
            console.log(12);
            const currencySpan = document.getElementById('balance');
            currencySpan.innerText = '£' + (parseFloat(currencySpan.innerText.replace(/[^0-9\.-]+/g,"")) * 100 - 1) / 100;
        });

        Livewire.on('post-updated.postId', postId => {
            alert(13);
            console.log(13);
           
        });

Edited: I have list of posts (post componnet) being displayed (grid component) and in post component i had an update button which when pressed fire the event which i was listening to from globally

 Livewire.on('post-updated', postId => {
}

I then created a sub component foe the button as i had to reuse the updated button logic elsewhere. but if i fired the SAME event (post updated).. all the post components being displayed in the grid were updating so i had to pass in the post id. and now cant get it to work globally..

what i have is a counter on the LAYOUTS page, so everytime user presses update, i increment the counter.. otherwise it would look odd.. it is recalculated if user refreshes the page

Edited 2- for now i have solved it by dispatching another non dynamic event - e.g. 'update-counter' and listening it from global js, and that works but ideally woul love to fix the original issue

1 like
3 replies
shez1983's avatar

hey - i am having same trouble. did you figure it out?

shez1983's avatar

thanks once again - this does help, the only issue is as i have like 6 posts (child component) on the Index page/component, it issues multiple dispatches/events etc..

Please or to participate in this conversation.