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.
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:
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>