1

I am using alpine.js in my laravel 7.x application. I am also using LaravelCollective/html in order to build a very basic form. The idea here is that I am attempting to change the href of my anchor tag based on what select input is picked. I am getting the following error: Undefined variable: dispatch

Here's my HTML/code:

<div x-data="{ url: '{{ route('dogs', ['dog'=>$selectedDog]) }}' }" class="px-4 py-5 sm:p-6">       
          <div class="mt-2">
            {{ Form::select('dogs', $dogs, null, 
              ['class' => 'mt-1 sm:leading-5',
              'x-on:change' => "$dispatch('selection-change', { value: $event.target.value })"]) }}
          </div>
          <div class="mt-6">
            <span class="block w-full rounded-md shadow-sm">
              <a 
                href="{{ route('dog', ['dog'=>$selectedDog]) }}" 
                x-bind:href="url"
                x-on:selection-change.window = "alert('test');"
                class="w-full"> 
                  Go to Dog
              </a>
            </span>
          </div>
</div>

Changing the select input should trigger the x-on:selection-change.window event bound to the window object on the anchor tag. it seems $dispatch is having issues, though.

randombits
  • 47,058
  • 76
  • 251
  • 433
  • Is that happening on PHP or JS side? Also, which version of Alpine are you running? – Hugo Aug 22 '20 at 18:15
  • I'm importing the latest `alpine@v2.x.x` from cdn. The exception seems to be thrown from the server, although I haven't changed any server-side code. – randombits Aug 22 '20 at 18:25

1 Answers1

1

PHP is seeing $dispatch and thinking it's a PHP variable, maybe need to escape the $ or use strings where interpolation is not allowed

Either:

  • escape $: 'x-on:change' => "\$dispatch('selection-change', { value: \$event.target.value })"
  • use single quote string: 'x-on:change' => '$dispatch("selection-change", { value: $event.target.value })'
Hugo
  • 3,500
  • 1
  • 14
  • 28