首页 > 解决方案 > Rails、turbolinks 和 javascript。如何避免出现重复的 Switchery 按钮?

问题描述

我正在我的 Rails 应用程序中实现 Switchery 按钮,并且 Turbolinks 已打开。当我导航到另一个页面,然后单击后退按钮时,该按钮被复制。

这是我的 Javascript 代码:

$(document).on('turbolinks:load', function() {
var elem = document.querySelector('.js-switch');
var switchery = new Switchery(elem, {className:"switchery switchery-small"});
});

html视图:

<b>Assign as administrator?<span> <%= f.check_box :admin, class:"js-switch" %></span></b>

截图: 查看

那么我该如何处理这个问题呢?

标签: javascriptruby-on-railsturbolinksswitchery

解决方案


多次调用可防止在同一元素上调用两次切换器,但这对 turbolink 没有帮助。由于页面是从缓存中获取的,当它们被添加到 DOM 时,它的点击/更改事件需要重新初始化。我发现的唯一方法是删除现有元素(看起来它们只是视觉元素),然后重新初始化它们。turbolinks:load 函数变成这样:

$(document).on('turbolinks:load', function(e) {
  // Delete existing switches if there are any...
  $(".switchery").remove();
  // As we removed all the switchery elements, we need fetch all of them again.
  var els = document.querySelectorAll(".js-switch");
  els.forEach(function(el) {
    new Switchery(el);
  })
});

推荐阅读