Remote/Ajax js requests in Jumpstart
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:
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:
- Submit a message to Rails with an AJAX request
- Save it in the controller
- 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)
- 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.
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.
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.