JavaScript 正在 Rails 应用程序加载 3 次

JavaScript is loading 3 times on Rails application

我有一个 ajax 函数在点击时被多次调用,而它应该只触发一次。

$(document).on('click', '.newGameItem', function() {
    console.log('start click event');
    var apiUrl = $(this).attr('data-api-string');
    var callType = $(this).attr('data-api-post-call');
    var apiKey = $(this).attr('data-api-key');
    var dataType = $(this).attr('data-api-data-type');
    var returnValue = $(this).attr('data-return-value');
    var currentGameWrapper = $(this).parent().parent().parent();

    console.log('before api call');
    getNewItem(apiUrl, callType, apiKey, dataType, returnValue, currentGameWrapper);
    console.log('after api call');
});

此点击事件在 turbolinks 加载事件中:

$(document).on('turbolinks:load', function() {  ...  }

我在 turbolinks 加载事件的顶部放了一个 console.log 并且可以确认这个文件中的 JavaScript 是 运行 3 次。我注意到当我在这个页面上时会发生这种情况,单击 link 到另一个页面然后点击后退按钮到这个页面但是当我从应用程序的其他地方点击页面时也会发生这种情况。

这个文件正在通过资产管道编译,我们在 body 标签上有 data-no-turbolink(实际上它似乎从来没有做任何事情。

知道为什么会发生这种情况或解决方法吗?将 turbolinks 从我的应用程序中完全移除目前对我来说不是一个选择。

谢谢

点击事件必须在 'turbolinks:load' 事件之外,这就是将其附加到 $(document) 而不是元素的目的。如果你有它,它会在每次加载页面时创建它。您的 javascript 应如下所示:

$(document).on('click', '.newGameItem', function() {
  // ...
});

$(document).on('turbolinks:load', function() {
  // ...
});