Server-side javascript calling into a controller


#1

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!

—Tim


#2

Would listening to the event ajax:success work for you?
More details here


#3

That actually helped a lot, though it means sending JSON back from the server rather than server-generated javascript. Thanks!


#4

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.


#5

In controller.connect() do:

window.thingController = this

Then you can reference window.thingController from your server rendered JavaScript.