Alpine.js event handler triggers inner livewire click handler twice

Viewed 1068

Hello to whomever sees this!

I have a simple livewire component to show / hide a dropdown in one of those angular material style chip autocompletes:

<span x-data="{ open: false }">
    <span @click="open = true">
        {{ $trigger }}
    </span>

    <span x-show="open" @click="open = false" @click.away="open = false">
        {{ $slot }}
    </span>
</span>

I use this in a livewire component that contains the input field, dropdown list and selected chips, like so:

    <x-input-dropdown>
        <x-slot name="trigger">
            <input type="text" wire:model="search">
        </x-slot>

        <ul>
            @forelse($options as $option)
                <li
                    wire:key="{{$loop->index}}"
                    wire:click="addItem('{{ $option }}')">
                       {{ $option }}
                </li>

            @empty

                <li>
                    No results found
                </li>

            @endforelse
        </ul>
    </x-input-dropdown>

I added the @click handler on the list itself to also hide when I select an option from the list. The problem is, with that handler in place, sometimes, the addItem() method gets called twice and I would get duplicates in the selected list.

I guess one question would be what would be a better approach, but I would also like to find out why this is happening? Is this intended? Is it a bug?

Thanks!

0 Answers
Related