Livewire firing event from global javascript callback function not working

Im trying to get a callback from the Livewire.emit function.

Blade File

    <button id="btn">Save</button> 

    @push('scripts')
        <script type="text/javascript">

            document.getElementById("btn").addEventListener("click", function() {

                Livewire.emit('getToken', (data) => {
                    // This nevers runs 
                    console.log(data);
                });

                foo(token);
            });

Livewire Controller

protected $listeners = ['getToken'];

public function getToken() {

    return 'token';
}

Problem is I cant seem to get the livewire.emit to get a callback with the returned value.

I know wire:click is a better option but the JS script goes on and makes a pop up. To avoid triggering browser anti-popup rules foo function must be directly called inside the click event listener.

1 Like