Reputation: 11
I have an application on Rails 7.1.3.4, upgraded from Rails 6. I am in the process of converting to using import maps for Javascript that the application uses. I am not using Turbo and Stimulus in this application. On one of my pages I invoke window.onload to run a javascript function residing in one of my javascript files. When I run the page, I get an error in the console saying that the function is not defined. I checked and the javascript file is loaded in the page, so I think that I'm defining my import maps and imports properly. I cannot figure out why the function cannot be accessed. Any help appreciated!
Here's the error message that I get in the console when the page is loaded:
Uncaught ReferenceError: setConfPicksDsply is not defined at window.onload (edit:2163:28)
Here's the relevant code in the view(it's at the end of the view file):
</div>
<%= javascript_tag "window.onload = function(){setConfPicksDsply();}" %>
<% end %>
The function setConfPicksDsply() resides in the file confnosprdpicks.js:
function setConfPicksDsply() {
// console.log("entering setConfPicksDsply()");
set_page_info_dialog("info_button");
setConfidencePoolSchedDsply();
set_picks_dsply();
set_sched_pnts_picked();
var nTimeToNextGame = time_to_next_game();
// console.log(nTimeToNextGame);
; if (nTimeToNextGame > 0)
{
// console.log("about to call setTimeout");
setTimeout(gm_expiration_confidence,time_adjusted_for_max_settimeout_val(nTimeToNextGame));
}
}
The javascript file in the HTML is:
<link rel="modulepreload" href="/assets/confnosprdpicks-60401ca8e1ca41b15e45331a22235f5dae41ed4cf88beda020a167403337da36.js">
and I can see that the function is in the file when I open it. Any ideas on how I can get the function to be recognized and run? Thanks!
Update 11/1/2024:
Hi Max, Thanks for your suggestions. I have been trying to get your first suggestion (place the function into global scope), as that would seem to be the least disruptive, short term way to fix the problem. But when I try this, I keep running into the same problem of the browser throwing an "Uncaught reference..setConfPicksDsply not defined" message. The js statement that I tried is "window.setConfPicksDsply = setConfPicksDsply" and I have located it inline in the page as follows:
<%= javascript_tag "window.setConfPicksDsply = setConfPicksDsply;
window.onload = function(){setConfPicksDsply();}" %>
I also tried this in application.js:
import "jquery"
// import "jquery-ujs"
import "confnosprdpicks"
window.setConfPicksDsply = setConfPicksDsply;
But I get the same error in either case.
Do I have the syntax correct or should I be putting the global assignment statement in another location?
Upvotes: 0
Views: 70