Necesito un script externo para agregar un elemento al DOM. Mi método Alpine debería reaccionar a ese cambio. Entonces, dentro de uno de mis métodos alpinos, agregué:
const observer = new MutationObserver(() =>{ const myIframe = document.getElementById('myIframe'); if (document.contains(myIframe)) { this.myIframeIsAvailable = true; observer.disconnect(); } }); observer.observe(document, { attributes: false, childList: true, characterData: false, subtree: true }); Desafortunadamente, el constructor del observador crea un nuevo alcance, por lo que no puedo acceder a this de Alpine allí. ¿Cómo puedo acceder a this allí?
Inicialmente pensé que podría agregar algo como on:childrenHaveChanged a mi plantilla, pero no puedo encontrar un evento coincidente para eso.
Debo haber cometido un error en mi sintaxis original, porque ahora el enfoque parece funcionar. Por si alguien está buscando una solución:
document.addEventListener('alpine:init', () => { Alpine.data('myApp', () => ({ elementHasBeenAdded: false, onClick(){ const observer = new MutationObserver(() =>{ const child = document.getElementById('child'); if (document.contains(child)) { this.elementHasBeenAdded = true; observer.disconnect(); } }); observer.observe(document, { attributes: false, childList: true, characterData: false, subtree: true }); const parent = document.getElementById('parent'); let child = document.createElement('div'); child.id = "child"; child.innerHTML = "I'm a child"; parent.appendChild(child); }, })) }); <div id="parent" x-data="{...myApp()}"> <p x-ref="paragraph">The value of elementHasBeenAdded is: <code x-text="elementHasBeenAdded">Loading ...</code></p> <p>Click here:</p> <button x-on:click="onClick()">Start observer</button> </div>