To handle dynamic event listeners in Livewire 3 using the #[On('event')] attribute, you can indeed bind dynamic parts of the event name to properties of your Livewire component. Here's a step-by-step example to illustrate how you can achieve this:
-
Define the Event Listener with Dynamic Binding:
You can use the
#[On('event')]attribute to listen for events dynamically. The dynamic part of the event name can be bound to a property of your Livewire component.use Livewire\Component; use Livewire\Attributes\On; class PostComponent extends Component { public $post; public function mount($post) { $this->post = $post; } #[On('post-updated.{post.id}')] public function refreshPost() { // Logic to refresh the post $this->post->refresh(); } public function render() { return view('livewire.post-component', ['post' => $this->post]); } }In this example,
post.idis dynamically replaced with theidof the$postproperty. -
Dispatching the Event:
When you want to dispatch the event, you need to ensure that the event name matches the dynamic pattern you defined in the listener.
// Somewhere in your application, e.g., in another Livewire component or a controller $postId = 1; // Example post ID $post = Post::find($postId); // Dispatch the event event('post-updated.' . $post->id); -
Example Blade View:
Here’s an example of how your Blade view might look:
<!-- resources/views/livewire/post-component.blade.php --> <div> <h1>{{ $post->title }}</h1> <p>{{ $post->content }}</p> </div>
Explanation:
-
Dynamic Event Binding: The
#[On('post-updated.{post.id}')]attribute listens for thepost-updatedevent with the specific post ID. The{post.id}part is dynamically replaced with theidof the$postproperty. - Event Dispatching: When dispatching the event, ensure the event name includes the specific post ID, so it matches the pattern defined in the listener.
This approach allows you to dynamically bind event listeners to specific instances of your Livewire component, making it more flexible and powerful.