How can one AlpineJS component send a message to, or call, another AlpineJS component?

37 views Asked by At

Let's say I have two Alpine components. How can component two send a message to component one? I would like to do this, but this won't work.

<div x-data="one()" id="one"></div>

<div x-data="two()"></div>

<script>

function one() {
  return {
    somethingHappened: function(thing) {
      console.log("Something happened:", thing)
    }
  }
}

function two() {
  return {
    init: function() {
      document.getElementById("one").somethingHappened("Wow!")
    }
  }
}

</script>
2

There are 2 answers

1
docd On

Use $dispatch to raise an event in one component, and listen for it using x-on in the other component.

See https://alpinejs.dev/magics/dispatch#dispatching-to-components

1
Magmatic On

One way of doing this is by using window events, like the following, but I'm not a big fan of this approach, because any component could register to listen for these calls. I would prefer a solution that guarantees only the specified receiving Alpine component will receive the event.

<div x-data="one()"></div>

<div x-data="two()"></div>

<script>

function one() {
  return {
    init: function() {
      window.addEventListener("something", function(event) {
        console.log("Something happened:", event.detail)
      })
    }
  }
}

function two() {
  return {
    init: function() {
      window.dispatchEvent(new CustomEvent("something", {
        detail: "Wow!"
      }))
    }
  }
}

</script>