Search code examples
javascriptalpine.jsgoogle-places-autocomplete

How to change Alpine.js x-data value in Google Maps Autocomplete javascript?


I am trying to implement Alpine.js with Google Autocomplete and I couldn't figure out how to make my modal shows up when I clicked on the dropdown result.

How do I set 'myModal' which is false by default in my x-data to be true in the event listener below?

    <body>
      <div x-data="{ myModal: false }">
       <input id="searchTextField" type="text" size="50" placeholder="Enter a location" 
        autocomplete="on" runat="server" />  

        <div x-show="myModal">
           Content..
        </div>
      </div>
    </body>

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
    <script>
        function initialize() {
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                //how to set 'myModal = true' here
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>

Solution

  • For this task (mutating Alpine.js state from an external script) you can use the global Alpine.store() object. Here we create a small myModal store object with a minimal open/close/toggle API and one internal state:

    <script>
    document.addEventListener('alpine:init', () => {
      Alpine.store('myModal', {
        active: false,
    
        toggle() {
          this.active = !this.active
        },
    
        open() {
          this.active = true
        },
    
        close() {
          this.active = false
        }
      })
    
    
      function initialize() {
          var input = document.getElementById('searchTextField')
          var autocomplete = new google.maps.places.Autocomplete(input)
          google.maps.event.addListener(autocomplete, 'place_changed', function() {
            // Open modal window
            Alpine.store('myModal').open()
          })
      }
    
      initialize()
    })
    </script>
    

    And in the template we access the modal's state like $store.myModal.active:

    <div x-data="">
        <input id="searchTextField" type="text" size="50" placeholder="Enter a location" 
            autocomplete="on" runat="server" />  
    
        <div x-show="$store.myModal.active">
            Modal content...
        </div>
    </div>