0

我第一次使用 Turbolinks 而不是 Rails(我使用的是 Django)。

再生产

https://glitch.com/edit/#!/join/dc628a17-3ccd-47b4-9921-8fb332aaebb1

源代码

  1. index.html

    <html>
    <head>
      <script defer src="/js/index.js"></script>
    </head>
    <body>
      Text and NO <script></script>!
    </body>
    </html>
    
  2. 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>
    
  3. index.js

    import Turbolinks from 'turbolinks'
    
    Turbolinks.start()
    
  4. 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了。

不是吗?

其他人做什么

  1. 同样的问题,但他的解决方案对我不起作用:https ://candland.net/rails/2019/03/13/rails-turbolinks-not-firing-js-on-load.html

感谢您的工作!

4

1 回答 1

0

我认为问题是在加载turbolinks:load之前被解雇了。about.js当 Turbolinks 呈现一个新页面时,它会将任何不存在的脚本添加到<head>,然后触发生命周期事件,例如turbolinks:load. 在这种情况下,它不会script在触发之前等待每个加载turbolinks:load。以下是可能发生的事情:

  1. index.html加载与index.js
  2. 导航about.html
  3. Turbolinks 合并about.js
  4. about.js开始下载
  5. Turbolinks 完成生命周期并触发turbolinks:load
  6. about.js完成下载并执行

因为turbolinks:load已经在 5 中触发了。about.js直到下一次加载才会调用 in 的回调。

您可能想尝试将 about.js 包含<body>about.html. turbolinks:load不需要监听器。

或者,尝试将您的 JS 包含在单个文件中,并可能使用页面内容来确定何时调用drawChart. 例如:

import Turbolinks from 'turbolinks'

// about.js content here

Turbolinks.start()

document.addEventListener('turbolinks:load', function () {
  var chart = document.getElementById('chart')
  if (chart) drawChart()
})
于 2019-09-09T08:04:34.983 回答