【问题标题】:$( document ).on('turbolinks:load', function() { not working$( document ).on('turbolinks:load', function() { 不工作
【发布时间】:2019-12-03 23:38:39
【问题描述】:

我正在尝试让我的 turbolinks 文档准备好工作。我的代码很简单

$( document ).on('turbolinks:load', function() {
  console.log("It works on each visit!")
})

这是使用 rails 6。该代码位于我的 application.js 文件的中间:

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
// Loads all Semantic javascripts
//= require jquery
//= require semantic-ui
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .
// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

$(document).on('turbolinks:load', function() {
$('.message .close')
  .on('click', function() {
    $(this).closest('.message').transition('fade');
  })
;
})

$( document ).on('turbolinks:load', function() {
  console.log("It works on each visit!")
})

我的 gemfile 中有 jquery 和 turbolinks gem,并且已经安装了 bundle。目前没有控制台日志显示,但也没有错误信息。

【问题讨论】:

  • rails-ujs 和 turbolinks 应该在 jquery 之前加载。使用document.addEventListener,希望它能起作用 - document.addEventListener("turbolinks:load", () => { console.log("loaded") });
  • @SalmanMahmud 为什么会有任何不同?
  • @max 我没有注意到这里缺少 require_self。
  • 'jQuery.on' 无论如何只是 addEventListener 的一个改进版。因此,如果前者不起作用,则后者没有理由起作用。

标签: javascript ruby-on-rails turbolinks ruby-on-rails-6


【解决方案1】:

问题是您的 mainfest 中没有 require_self 指令。

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
// Loads all Semantic javascripts
//= require jquery
//= require semantic-ui
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_self
//= require_tree .

它是一个单独的指令的原因是它可以让您影响文件的编译顺序。

【讨论】:

  • 您好,感谢您的回复。我在你告诉我的地方添加了 require_self 。控制台日志仍未在我的浏览器控制台中触发!
  • 嗯,在 sprockets 被 webpacker 替换后,它可能不会以同样的方式工作。尝试将其放在同一目录中的另一个文件中。
  • “它”是指带有 turbolink 的代码行吗?还是那个require_self?
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多