Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

126
Visualizações
How to use MutationObserver with AlpineJS and detect when an element is added to the DOM?

I need an external script to add an element the DOM. My Alpine method should react to that change. So inside one of my Alpine methods I added:

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 });

Unfortunately, the observer constructor creates a new scope, so I can't access Alpine's this in there. How can I access this in there?

Initially I thought I could add something like on:childrenHaveChanged to my template, but I can't find a matching event for that.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I must have made a mistake in my original syntax, because now the approach seems to work. Just in case anyone is looking for a solution:

Codepen

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda