I'm using Laravel 8 and Livewire. I have an application that shows items
objects from a table. When you click on an item
, it displays the item
details to the right.
<ul>
@foreach ($items as $item)
<li wire:click="show({{ $item->id }})" class="...">
{{ $item->name }}
</li>
@endforeach
</ul>
This works great, since the show()
method in the component will do anything it does, binding variables, and such...
Now, in the details section, I want to make a chart, a line chart. I have done it using d3js, and it works fine the first time I render the page, since my item
variable has already a default value (last item in the table)
When I click on other item
it shows the data, but the chart doesn't change its data, it is stuck with the data it got the first time it loaded.
I followed some solutions that said I have to send a contentChanged
event to the browser, but it doesn't seem to work.
In my component, after changing the selection I have:
$this->dispatchBrowserEvent('contentChanged');
To simplify things, in my blade, I have:
<script type="text/javascript">
window.addEventListener('contentChanged', e => {
alert('{{ $item->name }}')
})
</script>
Yes, it executes the function and show an alert, but the $item
has the data from the first time the page was loaded. It doesn't take the new $item
that changed on click.
What should I do?
CodePudding user response:
You can pass in data to the browser-event that is emitted,
$this->dispatchBrowserEvent('contentChanged', ['item' => $item]);
Then you can retrieve that information in the events data
attribute,
window.addEventListener('contentChanged', (e) => {
alert(e.detail.item.name);
});