Search code examples
laravellaravel-livewire

Livewire Wire Elements Modal not triggering events


I am using Wire Elements Modal, It is working properly but events are not getting triggered from modal component. My modal is like below

class AddUser extends ModalComponent
{
    public function render()
    {
        $this->emit('refresh');
        $this->dispatchBrowserEvent('contentChanged');
        return view('add-user');
    }
}

In above component two events are emitted and below code listens to them. But below code is not triggered at all. If I use normal Livewire component then below code is triggered without any issue. The problem is only if I use WireElements/modal component.

In layout file I have listener like below

<script>
        Livewire.on('refresh', () => {
           //code
        })
        window.addEventListener('contentChanged', (e) => {
            //code
        });
</script>

This works in normal livewire component but not in modal.


Solution

  • The initial render will not handle emits or browser events since at that point there isn't even a rendered document. What you can do is use wire:init, to trigger your events in the first render:

    class AddUser extends ModalComponent
    {
        public function render()
        {
            $this->sendEvents();
            return view('add-user');
        }
    
        public function sendEvents()
        {
            $this->emit('refresh');
            $this->dispatchBrowserEvent('contentChanged');
        }
    }
    
    <div wire:init="sendEvents">
        
    </div>
    

    I have tested this myself and it triggers each request cycle.