Dispatch from within observer

I have a controller with an MutationObserver
I would like that observer to dispatch an event as described in " Cross-Controller Coordination With Events’, but I just get Dispatch not available.

Uncaught ReferenceError: dispatch is not defined
    at MutationObserver.<anonymous> 
    let observer = new MutationObserver(function(params) {

        <snipped actual code >

        console.log('dispatch autosave event')
        dispatch('autosave')

    });

what am I missing here?

https://stimulus.hotwired.dev/reference/controllers#cross-controller-coordination-with-events

It’s important to realize that everything in Stimulus (well, not everything, but a lot) runs inside its own MutationObserver. You might be nesting those, and I don’t know off-hand if that’s possible or allowed. Note that nothing in the example you linked to uses that kind of indirection, but rather keeps it all on one level, letting one controller call another by directly notating in the DOM what event should call what controller.

Walter

Have you tried: this.dispatch("autosave") ?

You will need to use this.dispatch but be sure you are referring to the right this.

If you use a function() { supplied to the mutation observer - this will actually be the mutation instance (most likely).

Instead you probably want to use an arrow function for your callback.

() => { this.dispatch(...); }

Have a read of

Hope that helps.