Home > database >  livewire dispatchBrowserEvent is not triggering alert
livewire dispatchBrowserEvent is not triggering alert

Time:05-20

I have a livewire component which has an update() function to update the component when it changes. The update() function is called and updates the item in the database as required. At the end of this function i run a dispatchBrowserEvent() to confirm the update but the corresponding function in my js file is not being called and thus the alert is not being triggered.

I have been using this method from the docs https://laravel-livewire.com/docs/2.x/events#browser

The livewire component:

<?php

namespace App\Http\Livewire;

use App\Models\Item;
use Livewire\Component;

class EditItem extends Component
{
    public int $item;
    public string $date = '';

    public function render()
    {
        return view('livewire.edit-item');
    }

    public function update()
    {

        $item             = Item::find( 1 );
        $item->date       = now();

        $item->save();

        $this->dispatchBrowserEvent('update-item', ['item' => $item->id, 'date' => $item->date]);

    }
}

its blade file:

<div>
    <button wire:click="update">Update Me!</button>
</div>

in my app.js I have the following:

jQuery(document).ready( function($) {
    /** LIVEWIRE EVENT ACTIONS **/
    window.addEventListener('update-item', event => {
        alert( 'Date updated to: '   event.detail.date   'on item with id of '   event.detail.item );
    })

});

CodePudding user response:

So it turned out i hadn't ran npm run dev so the javascript didn't exist. after running this all was good.

CodePudding user response:

remove this code in app.js

jQuery(document).ready( function($) {
    /** LIVEWIRE EVENT ACTIONS **/
    window.addEventListener('update-item', event => {
        alert( 'Date updated to: '   event.detail.date   'on item with id of '   event.detail.item );
    })

});

in blade

<div>
        <button wire:click="update">Update Me!</button>
 
    <script>
        document.addEventListener('update-item', event => {
           alert( 'Date updated to: '   event.detail.date   'on item with id of '   event.detail.item );
        })
    </script>
</div>
  • Related