Rails, turbolinks and javascript. How to avoid duplicate Switchery button appear?

624 views Asked by At

I'm implementing Switchery button in my Rails app and Turbolinks is on. When I navigate to another page, and then click the back button, the button is being duplicated.

Here is my Javascript code:

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

Html view:

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

Screenshot: View

So how can i handle this problem ?

2

There are 2 answers

3
eikes On

Multiple calls

You can filter out existing elements that have already been called by looking for data-switchery="true".

  var elem = document.querySelector('.js-switch:not([data-switchery])');

0
radalin On

Multiple calls prevents switchery being called twice on the same element but it's not helpful with turbolinks. As page is fetched from cache, it's click/change events needs to re-initialized when they are added to DOM. The only way I found was to remove the existing elements (it looks like they are just visual elements anyway) and then re-initialize them. turbolinks:load function becomes something like this:

$(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);
  })
});