Have Stimulus wait for Dom changes using MutationObserver custom event listener before continuing

Viewed 12

I am writing a Stimulus controller that has a function which needs wot wait for DOM changes before it can continue (As a Turbo Stream response needs to update a frame). Before the DOM change, it can't find the target, but it should be able to AFTER the DOM change.

I have successfully enabled MutationObserver, which is able to tell me that the child element was added--but this happens after the function/action is looking for it.

Therefore I found this article on how to use Mutation Observer to add a custom Event Listener.

I've gotten it to work as far as until the last step, where we code the Promise.

When I run the code, I get

undefined is not an object (evaluating "el.innerText.includes(text)

I tried changing it to

document.getElementByTagName(el).innerText.includes(text)

But that returned that it's not a function.

The instantiation of the MutationObserver is inside my connect() method:

connect() {
    const observer = new MutationObserver( list => {
      const evt = new CustomEvent('dom-changed', {detail: list});
      document.body.dispatchEvent(evt)
    });
    observer.observe(document.body, {attributes: true, childList: true, subtree: true});
  }

the waitforText(el, text, maxWait=5000) function is a controller action currently.

I then run this.waitForText("h1", "Settings for") inside the function I need it to wait. I'm merely using a h1 for testing before I put it on an element that is within the same frame as that h1.

0 Answers
Related