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

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