Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bep
Last active November 12, 2023 09:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bep/a9809f0cb119e44e8ddbe37dd1e58b50 to your computer and use it in GitHub Desktop.
Save bep/a9809f0cb119e44e8ddbe37dd1e58b50 to your computer and use it in GitHub Desktop.
export function bridgeTurboAndAlpine(Alpine) {
document.addEventListener('turbo:before-render', (event) => {
Alpine.deferMutations();
});
document.addEventListener('turbo:render', () => {
if (document.documentElement.hasAttribute('data-turbo-preview')) {
return;
}
Alpine.flushAndStopDeferringMutations();
});
// Cleanup Alpine state on navigation.
document.addEventListener('turbo:before-cache', () => {
Alpine.mutateDom(() => {
document.body.querySelectorAll('[x-data]').forEach((el) => {
if (el.hasAttribute('data-turbo-permanent')) {
el._x_ignore = true;
} else {
Alpine.destroyTree(el);
// Turbo leaks DOM elements via their data-turbo-permanent handling.
// That needs to be fixed upstream, but until then.
let clone = el.cloneNode(true);
el.replaceWith(clone);
}
});
});
});
}
@khrome83
Copy link

@bep do you include alpine, turbo, and this GIST and that is it? There is no need for another adapter or anything?

@bep
Copy link
Author

bep commented Sep 17, 2021

@khrome83 yes -- but you need the stopObservingMutations() exported -- it's in a PR, but not merged, yet ...

@khrome83
Copy link

khrome83 commented Sep 23, 2021

Looks like we have a alternate path here.

livewire/livewire#3151 (comment)

It was added as part of Alpinejs v3.4.1. https://github.com/alpinejs/alpine/tree/v3.4.1

Any chance @bep you could update your Gist with that support. I am trying to make sense of it and wrap my head around it.

@bep
Copy link
Author

bep commented Oct 6, 2021

@khrome83 I have added a comment to the PR you mentioned. I have also updated my Gist (but that requires a patched version of Alpine).

@khrome83
Copy link

khrome83 commented Oct 6, 2021

@calebporzio can you help here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment