'Where to place Javascript used in one page only in Rails 7 with importmap
When using Rails 7 with import maps, where do I put code that should be executed by one view only?
Specifically, I have a view that needs to run some Javascript code on load. My Javascript looks something like this:
import {TheController} from "./TheController"
let controller = new TheController();
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
controller.onLoad();
}
};
How do I setup the Javascript environment so that the document.onreadystatechange code is executed only by the desired view? (Everything almost works when I put this code in a file imported by application.js, but then it gets executed by every view.)
I suspect the answer is to create separate importmaps and importmap_tags; but, I can find any demonstrations of how to do that in Rails 7.
Solution 1:[1]
As @Azrklm points out, the answer is contained in this video https://youtu.be/PtxZvFnL2i0?t=1287 beginning at time 21:38.
Suppose we have some JavaScript that we want to run only on a view called FancyView. Here are the steps
Place the code unique to
FancyViewin its own file, sayFancyView.js(and remove it fromapplication.js, if necessary).Add a line for
FancyView.jsto the importmap:pin "FancyView"Add the line
<%= yield :head %> toapplication.html.erb`. (This tells Rails that individual views/layouts may want to add additional information to the web page's head.)<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> <%# This loads application.js %> <%= yield :head %>Add a
javascript_import_module_tagto the view:<% content_for :head do %> <%= javascript_import_module_tag "FancyView" %> <% end %>
Solution 2:[2]
If anyone has a similar problem finds this question, I found the answer from @Zack to be perfectly concise and exactly what I needed, BUT with 2 important caveats:
I couldn't use the capcase naming convention for my js.
FancyViewneeded to befancyView.The javascript_import_module_tag should come after your javascript_importmap_tags
<%= javascript_importmap_tags %> <%= yield(:head) %>
This is also now explained on the rails github page: https://github.com/rails/importmap-rails#selectively-importing-modules
Thanks @Zack!
Solution 3:[3]
DHH explains it pretty well have a look plz https://youtu.be/PtxZvFnL2i0?t=1287
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rogerkk |
| Solution 2 | Jason N |
| Solution 3 | Azrklm |
