Laravel balde component with Alpinejs to pass back data to parent model

Viewed 71

Having the following blade component used with alpinejs how can I pass the model value to the parent?

<x-choises
  x-model="formData.association"
  :options="$associations"
  :selected="$currentAssociation"
  class="m-expertsearchcomponent__associations"
  label="{{__('Associations', 'namespace')}}"
/>

the markup of the component which will init another aplinejs component

<div @class($attributes['class'])>
  <div class="m-expertsearchcomponent__select">
    <select class="nochoices" x-data="cselect" x-ref="select">
      <option selected value="">{{ $label }}</option>
      @foreach ($options as $option)
        <option value="{{ $option->id }}">{{ $option->title }}</option>
      @endforeach
    </select>
  </div>
</div>

here is the js from childcomponent

import Choices from "choices.js";
import Alpine from "alpinejs";

Alpine.data('cselect', function () {
  init: {
    if(!this.$refs.select) return;

    const self = this;
    const currentValue = this.$root._x_model && this.$root._x_model.get()

    const choice = new Choices(this.$refs.select, {
      itemSelectText: '',
      removeItems: true,
      allowHTML: false,
      removeItemButton: true,
    });

    console.log(currentValue)
    if(currentValue) {
      choice.setChoiceByValue(currentValue)
    }

    this.$refs.select.addEventListener('change', function (event) {
      return event.target.value;
      self.$root.select._x_model.set(selectValue)
    })

    this.$refs.select.addEventListener('removeItem', function (event) {
      //self.$refs.select._x_model.set(null)
    })
  }
});
0 Answers
Related