在 Rails 5 中使用可排序.js和涡轮链接



我有一个 Rails 5.1 应用程序,其中我正在使用 https://www.kryogenix.org/code/browser/sorttable/中的可排序.js库来对表进行一些简单的客户端排序。

我遇到了一个问题,当页面首次加载时,表格排序不起作用。 (它只是根本没有响应。 如果您随后手动重新加载页面(cmd-R 或等效项(,那么它确实有效。

经过一番搜索,我认为问题是由涡轮链接引起的。 像这样的帖子,以及其他建议如何修改JS代码来解决它:Rails javascript仅在重新加载后才能工作

要引用该页面上的答案,您必须通过执行以下操作来告诉涡轮链接加载:

document.addEventListener("turbolinks:load", function() {
my_func();
})

但是,我不是JS专家,因此有点讨厌在可排序.js代码中胡闹太多。 我正在寻求帮助,以最小的侵入性方法来解决问题。

发布一个有效的解决方案,为了未来的谷歌用户。

我必须做两件事才能让它工作:

1:注释掉 init 函数顶部的行,以防止它运行多次。 所以我在 sorttable 中的 init 函数的顶部.js看起来像这样:

sorttable = {
init: function() {
// Had to comment these top to out to get things to work with turbolinks
// quit if this function has already been called
//if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
//arguments.callee.done = true
  1. 将此代码添加到文件的其他位置。 (我个人将其添加到"window.onload = sorttable.init;"的行之后

    ;
    document.addEventListener("turbolinks:load", function() {
    sorttable.init();
    })
    

最新更新