Events

Dispatching events from Livewire components

$this->dispatch('event-name', key: value);

Direct to another component

$this->dispatch('event-name')->to(MyComponent::class);

Dispatching events from blade templates

<button wire:click="$dispatch('event-name', { key: value })"> ... </button>

Dispatching events from from objects

$this->component->dispatch('notify', 'Lesson form initialized');

Direct to another component

<button wire:click="$dispatchTo('my-component', 'event-name', { key: value })"> ... </button>

When using the $dispatchTo method you must define the full path to the component path using dot notation.For example, to dispatch an event to the courses/programming/edit component you would use:

$this->dispatchTo('courses.programming.edit', 'some-event');

Registering event listeners

Registering event listeners using the $listeners property

protected $listeners = ['event-name' => 'method'];

Registering event listeners using the On attribute

use Livewire\Attributes\On;

#[On('event-name')]
public function doStuff() { }

Refreshing Techniques

Refreshing a list of items after an action has been performed

Scenario: You're working with a main form that includes a list of items. Each item is a separate Livewire component, referred to as 'ListRow'. These items are iterated over within the main component. The goal is to refresh this list after an action has been performed.

Dispatch an event from the 'ListRow' component after an action has been performed. For example, when an item is deleted, dispatch a 'refresh-list' event.

// ListRow.php
public function deleteItem($itemId){
    // Delete the item
    Item::find($itemId)->delete();
    // Dispatch a refresh event to the main component
    $this->dispatch('refresh-list');
}

There are several approaches to achieve this:

Add a listener to the main component and call the $refresh method.

// main-component.blade.php

// list in main component
@foreach ($items as $item)
    <livewire:list-row :item="$item" :key="$item->id" />
@endforeach
// MainComponent.php
protected $listeners = ['refresh-list' => '$refresh'];

Trouble Shooting

Event listeners not working

Make sure the Livewire component blade views are on the same page.