Proper AlpineJS Integration with Liveview

Just in case this helps… I was playing with Alpine again and found a way around a few issues I had previously had with something similar.

Instead of having variables inside x-data, use an attribute and a mutation observer.

<div x-data="{foo: null}" foo={@foo} />
init() {
  this.foo = this.$el.getAttribute("foo");

  this.observer = new MutationObserver((mutations) => {
    mutations.forEach((m) => {
      if (m.attributeName == "foo") {
        this.foo = this.$el.getAttribute("foo");
      }
    });
  });

  this.observer.observe(this.$el, { attributes: true });
}
3 Likes