I’ve got a fairly standard Rails app, and I’m using Stimulus to do all the side effects for an ajax search box. When the form is sent to the server, I’d like it if the server-side generated javascript could just call a method on the controller, but I can’t think of how I can do that. Guidance would be appreciated!
I had a similar problem when porting one of our apps to stimulus. I ended up generating JSON on the server side, that wold define events to fire on the client. JSON defines the name of the event to fire, target element(s) for the event and any data to pass onto event handler.
Then I wrote a small event dispatcher in JS that would parse the JSON and fire the appropriate events.
This way the backend and frontend logic are nicely decoupled and you can have many components react to the dispatched event.
No need to tie thing to existing event like ajax:success and alike.