我第一次使用 Turbolinks 而不是 Rails(我使用的是 Django)。
再生产
https://glitch.com/edit/#!/join/dc628a17-3ccd-47b4-9921-8fb332aaebb1
源代码
index.html
:<html> <head> <script defer src="/js/index.js"></script> </head> <body> Text and NO <script></script>! </body> </html>
about.html
:<html> <head> <script defer src="/js/index.js"></script> <script defer src="/js/about.js"></script> </head> <body> Text and NO <script></script>! </body> </html>
index.js
:import Turbolinks from 'turbolinks' Turbolinks.start()
about.js
:function drawChart() { console.log("I will drawChart() here") } // drawChart() <--- this is commented on purpose here, with this it works! document.addEventListener('turbolinks:load', drawChart)
问题
如果我从页面开始/index
,然后通过链接导航到/about
没有任何反应!
如果我现在回到/index
我可以在控制台中看到日志:I will drawChart() here
。所以听众正在工作。
如果我从它开始(刷新),/about
它会在控制台中打印消息,以便侦听turbolinks:load
器在刷新时运行该函数drawChart()
。
我期待什么,我做了什么
drawChart()
我也需要在第一次导航中调用该函数/about
。
所以我想在文件中使用直接调用(drawChart()
如您所见,在源代码中对此问题进行了评论)并且它有效。
但我认为这不是好方法,特别是因为如果我继续/about
刷新页面,它会被调用两次!
在我看来这太hacky了。
不是吗?
其他人做什么
- 同样的问题,但他的解决方案对我不起作用:https ://candland.net/rails/2019/03/13/rails-turbolinks-not-firing-js-on-load.html