admin管理员组

文章数量:1399992

I have a laravel emit in a liveware blade file as follows:

<script>
    document.addEventListener('livewire:load', function () {
        setTimeout(()=>{
            Livewire.emit('nextSlot');
        }, 4000);
    });
</script>

This does not work, it does not emit the nextSlot function in the respected php file.

Note, this hwoever does work as expected:

<button wire:click="nextSlot">
    Next Slot
</button>

Any reason why my emit inside the <script> tags don't work? And what can I do to emit an event after a setTimeout?

I have a laravel emit in a liveware blade file as follows:

<script>
    document.addEventListener('livewire:load', function () {
        setTimeout(()=>{
            Livewire.emit('nextSlot');
        }, 4000);
    });
</script>

This does not work, it does not emit the nextSlot function in the respected php file.

Note, this hwoever does work as expected:

<button wire:click="nextSlot">
    Next Slot
</button>

Any reason why my emit inside the <script> tags don't work? And what can I do to emit an event after a setTimeout?

Share Improve this question edited May 17, 2021 at 8:41 Asaad Mahmood asked May 17, 2021 at 7:37 Asaad MahmoodAsaad Mahmood 4266 silver badges20 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

If you are using Livewire 3 you can use the code below:

Livewire.dispatch()

Link: Livewire Events

You need to add an event listenter on your Component for your client event:

protected $listeners ['nextSlot'];

The above will listen for a nextSlot event being raised and call a method in you Component called nextSlot. If your event name and method do not match, you would need to specify the name of the method to be called.

protected $listeners = ['nextSlot' => 'methodName'];

Also note that your nextSlot event will be fired just once after 4 seconds. Not sure if that is what you want or if you want the event fired every 4 seconds. If you want the latter, replace setTimeout() with setInterval().

document.addEventListener('livewire:load', function () {
    setInterval(() => Livewire.emit('nextSlot'), 4000);
})

Use window.Livewire.emit('func', 'data');

If your wire:click works but the Livewire.emit isn't working this might be caused by the different type. The click is a specific event that calls the related method directly while emit only calls the method, if the listeners array contains it. Have you added it to the listener? If you share you ponent code, it should be easier to debug.

本文标签: laravelLivewareemit not working in global javascriptStack Overflow