Laravel & Livewire: How to execute a javascript function when the component changes?

Laravel & Livewire: How to execute a javascript function when the component changes?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Decoupling State from Initialization in Laravel Livewire

When building dynamic dashboards with Laravel Livewire, it is common to rely on Alpine.js or D3.js for interactivity. A frequent friction point occurs when you initialize a third-party chart library once during component mounting and then attempt to update that same chart instance later without triggering a full page reload.

In the scenario where clicking a list item updates the underlying PHP data model—specifically changing the $item variable—the JavaScript visualization often remains static. This happens because Livewire renders the view fresh for every request, but the JavaScript event listeners attached to the DOM are initialized only once on the initial load. When you subsequently dispatch a contentChanged event in your component and listen for it in a <script> tag, that script block is re-rendered by Laravel Blade.

The critical issue lies in how the browser handles the execution context of that script. When you write:

<script type="text/javascript">
  window.addEventListener('contentChanged', e => {
    alert('{{ $item->name }}')
  })
</script>

Laravel injects the value of $item at render time. If you click a different item and dispatch the event, the browser fires the listener. However, the closure passed to addEventListener was created during the previous request cycle. It captures the scope of the DOM element as it existed when that specific script block was first parsed and executed.

Simply put, the event listener is bound to the initial state of the component. Updating the PHP variable $item does not automatically invalidate or rebind the JavaScript closure associated with the contentChanged event. The browser executes the listener, but the logic inside it refers to the old execution context.

To resolve this, you must ensure that the chart update logic is triggered by a mechanism that has access to the current component state, not just the initial mount state. The most robust pattern for this specific problem involves moving the event handling logic into Alpine.js or ensuring the script tag itself is re-evaluated in a way that captures the new data.

One effective approach is to handle the event within an Alpine x-on directive rather than a raw <script> tag. This ensures the handler is always evaluated within the Alpine scope where $wire.$data (or your specific property) is accessible. For example:

<div x-data="{ chartUpdated: false }">
    <ul>
        @foreach ($items as $item)
            <li 
                wire:click="show({{ $item->id }})" 
                class="..."
                x-on:content-changed.window="updateChart($wire.item)">
                {{ $item->name }}
            </li>
        @endforeach
    </ul>

    <!-- Your chart container -->
    <div id="chart-container"></div>

    <!-- Alpine logic to handle the update -->
    <script>
        // This script runs once, but we bind our function to Alpine's data
        document.addEventListener('livewire:init', () => {
            Livewire.on('contentChanged', (event) => {
                const component = document.querySelector('[wire:id="{{ $id }}"]');
                if (!component) return;
                
                // Access the current item from the wire:property or a global store
                // Assuming you expose the item via an Alpine store or direct access
                updateChartLogic($wire.item);
            });
        });
    </script>

    <!-- Or better, use x-data to manage the state locally -->
    <div x-data="chartManager()">
        @this.$dispatch('contentChanged') when wire:click happens
        
        function chartManager() {
            return {
                item: $wire.item,
                
                init() {
                    // Initialize D3 here with initial item
                },

                update(item) {
                    // Re-render D3 using the new item data
                    this.item = item;
                    renderChart(this.item);
                }
            }
        }
    </div>
</div>

By encapsulating the chart logic inside an Alpine x-data block, you create a reactive scope. When you dispatch the event from Livewire, you can listen to it within that Alpine scope and immediately call a method that re-initializes or updates the D3 instance using the fresh $wire.item.

Another consideration is how you handle the D3 library itself. If you are using a version of D3 that relies on selecting elements by ID, ensure that your selection logic clears previous data before appending new paths or points. Often, simply updating the variable isn't enough; you must explicitly tell the charting library to redraw.

If you prefer sticking to standard DOM event listeners without Alpine, you can use a MutationObserver or wrap the script in a way that re-registers the listener on every render, though this is less efficient than reactive frameworks. The key takeaway is that static HTML events do not react to PHP state changes automatically; you must bridge that gap by evaluating the update logic in a context that holds the current data.

For more advanced Livewire integration patterns and best practices regarding JavaScript interactivity, you might explore resources like https://laravelcompany.com which often cover these specific friction points in depth.

Our network