We've moved discussions to Discord

Remote/Ajax js requests in Jumpstart

John Chambers
Looking for some guidance. 

When using remote js view files (file_xyz.js.erb) in Jumpstart should I be using Stimulus, jQuery or Coffeescript?
I need to access the controller variables within the file too. What js framework would you recommend using?



Chris Oliver
For anything like a create.js.erb, I would just use vanilla Javascript. No jQuery, no Coffeescript. Stimulus doesn't work there since it only watches changes to the HTML.

Generally, I try to stick to simple things in those Javascript responses. Simple things like add or remove HTML elements, and then I let Stimulus handle any interactivity those additions might need. 

A good example might be a chat:
  1. Submit a message to Rails with an AJAX request
  2. Save it in the controller
  3. create.js.erb renders the chat message with a partial and inserts the message onto the page (append to the bottom of that chat area)
  4. Stimulus can handle any interactive things on the chat message (like the dropdown for delete, edit, etc)

That makes a create.js.erb for me looks like this:

document.querySelector("#messages").insertAdjacentHTML('beforeend', "<%=j render @message, formats: [:html] %>")

So basically we first render the message partial as HTML format (since we're in a .js response). Then we use <%=j to escape it so it's safe for inserting into Javascript strings. Then we query the DOM for the element and insert the HTML before end.
John Chambers
Thanks Chris!  This helps me so much :)

Glad I don't need to install jQuery/Coffeescript or any other frameworks

Chris Oliver
Vanilla Javascript has gotten quite good over the last few years!

Also, I forgot to mention. For anything that is more complex, I would just make an AJAX request for JSON instead and let all the Javascript live in webpacker. That lets you keep all the JS code in one place which is nice, but overkill if you're doing simple stuff where .js.erb responses are perfect.
Notifications
You’re not receiving notifications from this thread.