laravellaravel-livewirelivewire-3

Emit an event from global JS in Livewire 3


I try to migrate from livewire 2 to version 3 and the last blocker is, how to emit a livewire event from global javascript.

So, in Livewire2, it was done this way (and it worked):

window.register_lock = function(register_id) {
    swal({
        title: 'question',
        text: 'Rly?',
        icon: 'warning',
        buttons: true,
        dangerMode: true,
    }).then((confirmed) => {
        if (confirmed) {
            Livewire.emit('register_lock', register_id);
        }
    });
};

So, in detail, we speak about the Livewire.emit line. After upgrading to Livewire 3, this line do not work anymore but all the docs are only speaking about performing this inside a component are things like this. I do not have a component and I just want to fire a Event to my server, so it executes the action behind the "yes" button.

Any tips?


Solution

  • Livewire V3 introduced many breaking changes as it was a major update and the upgrade guide and automatic upgrader mentions some of these changes.

    When firing Livewire events you now need to provide any parameters using Key Value pairs even if the listener only accepts 1 parameter. You also need to specify a matching name for the argument on the method that is fired inside your component.

    You can see the documentation on how to implement Livewire events here: Events | Laravel Livewire

    Here's an example of how events are now fired when they include parameters.

    Livewire.dispatch('post-created', { postId: 2 })
    

    You may also note the method is no longer named 'Emit' but 'dispatch'

    This is how your code should look after implementing these changes:

        if (confirmed) {
            Livewire.dispatch('register-lock', {registerId: register_id});
        }
    

    Note: I changed the name of the event that's being fired to match the convention set out in the Livewire documentation.

    As I mentioned earlier you must make sure the method that will be executed is expecting a parameter with the same name as the key you provided earlier as so:

        #[On('register-lock')] 
        public function lockRegister(int $registerId)
        {
            // Your logic here
        }
    

    Don't forget to import the attribute:

    use Livewire\Attributes\On; 
    

    For a list of all breaking changes introduced in the V3 update the documentation has an Upgrading section.