Hotwire Discussion

"Missing target element" when using dispatch between 2 controllers

I just got started with StimulusJS and I am in the process of integrating it with my WordPress plugin. For my use case I have lot of input fields on different areas of a page. In one area I have an input to collect a book’s ISBN and beside it a button that takes the user input then fetches data via an API. When the data is returned it used to update inputs in another section of the page.

So I am using this.dispatch() to pass data between 2 controllers are per the StimulusJS tutorial.

However, when I do this I am getting an error about a missing target element. You can see an abridged version of my code here with the same error.

https://glitch.com/edit/#!/branched-mirage-soccer

Does anyone here have a workaround?

Check this. Is it what you need? Glitch :・゚✧

To be honest I didn’t know that Stimulus has this.dispatch feature. Since early days I’ve used stimulus-use and seems the feature later implemented in Stimulus works the same way. Check this explanation stimulus-use/use-dispatch.md at main · stimulus-use/stimulus-use · GitHub

1 Like

Thanks for looking at this @woto

After I posted this I saw a closed GH issue for the problem I am having and it too suggested moving the second controller to wrap the first controller. However, this isn’t really viable for my use case as both div containers can only be siblings in how thing are on the WordPress post editor screen.

I was thinking of wrapping both “sibling” controllers with a “parent” controller that will catch the dispatched event then pass it down back to the appropriate “sibling” controller.

Or, I could just reference the inputs via document.getElementByID() and not use data targets. With this way, I get back syntax highlighting in my IDE, plus I wont trip-up on the odd naming convention of data targets.

And, I did look at that util library but it said something about not being v3 compatible.

Sorry lack knowledge of English put me in situation that I don’t fully understand that your problem solved or not :slight_smile: anyway check example 2, where ...@window... used. It just use JS events under the hood which allow to dispatch event to any arbitrary located controller (parent, child, sibling).

I just tried it with @window and it works! Thank you so much!

1 Like