I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event. Below is an excerpt from my Laravel Livewire component:
protected $listeners = [
'reportFilterUpdated' => 'reportFilterUpdated',
'eventListened' => 'eventListened',
];
public function render()
{
$this->generateChartData();
return view('dashboard');
}
public function generateChartData()
{
// Some other unrelated codes
$this->emit('reportFilterUpdated');
}
Here is the relevant JavaScript code I'm using:
document.addEventListener('DOMContentLoaded', () => {
Livewire.on('reportFilterUpdated', _ => {
console.log('event listened');
});
});
Current output in the browser's console (it never stops printing):
dashboard.js: (97) event listened
Does anyone have any suggestions on how to ensure the action only executes once per emitted event? My goal is for 'event listened' to be printed only once in the console regardless of the number of emissions from my Livewire component. Any help would be greatly appreciated. Thanks.