javascript - rails : Page specific javascript running on every page if visited in same window

标签 javascript ruby-on-rails browser-cache turbolinks

我想为某个特定页面运行 javascript。为此,我在布局文件中创建了元标记,如下所示:

<%= tag :meta, name: :psj, action: action_name, controller: controller_name %>

我还创建了一个 init.js 文件,它将由应用程序 list 文件加载。

# init.js
var Page, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Page = (function() {
  function Page() {
    this.action = bind(this.action, this);
    this.controller = bind(this.controller, this);
  }
  Page.prototype.controller = function() {
    return $('meta[name=psj]').attr('controller');
  };
  Page.prototype.action = function() {
    return $('meta[name=psj]').attr('action');
  };
  return Page;
})();
this.page = new Page;

这是需要在特定操作上运行的特定 Controller 的 javascript 文件:

# scans.js
$(document).on('turbolinks:load', function() {
  if (!(page.controller() === 'scans' && page.action() === 'index')) { return; }

  var ajax_call = function() {
    $.get("/scans.js", { }, function(table) {
      $("#scans").replaceWith(table);
    });
  }

  var interval = 1000 * 60 * 1 ;
  setInterval(ajax_call, interval);
});

这非常适合 scans#index 页面。现在,在访问此页面后,如果我单击任何链接以加载同一窗口中的其他页面ajax_call 代码将运行,但情况并非如此。

相反,如果我在不同的窗口中打开其他页面,它工作正常(ajax_call 不运行)。它是否与浏览器的缓存或 turbolinks 缓存有某种关系,不确定问题的原因是什么。

最佳答案

您遇到的问题是您已经对 Turbolinks 进行了检测,但实际上并没有监听页面更改事件来操纵状态。即,当页面发生变化时,您需要清除您的间隔。 Turbolinks 不处理浏览器打开新窗口和导航到 URL(例如 super +单击),因此它在这些情况下有效。

关于javascript - rails : Page specific javascript running on every page if visited in same window,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52390621/

相关文章:

ruby-on-rails - 从 Rails 中的成员中过滤掉管理员

angular - 在 IIS 上部署 Angular 7 应用程序后清除浏览器缓存

javascript - 检测图像是否被缓存

javascript - 在此 javascript 动画中,第二次动画无法正常工作

ruby-on-rails - 当使用 attr_encrypted 进行 activerecord 存储时,我得到 nil 和 Empty

javascript - 在javascript中使用按位或转换为整数

ruby-on-rails - Ruby on Rails : Configure API in initializer in development

javascript - 禁用 Mozilla Firefox 存储 javascript

Javascript在数组中添加相同的元素N次

javascript - Node.js 中的属性