0

I am hosting a sample application to clearly elaborate by problem. Try to visit the site, then follow another page link, using browser back return to previous page then to another page using browser forward button(You can continue move back and forth) "Hope you see what i am talking about"

Code: Previous page

<h1>Form page</h1>
<div id="rating-form">
  <label for="rating-form"> Rating </label>
</div>

Loading my js code using

$(document).ready(function(){});

doesn't work until full page load( as i espect). So i followed this solution

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

  $('#rating-form').raty({

    path: '/assets/',
    scoreName: 'review[rating]', 
    score: function(){
        return 0
    },


  });

});

resulted to the bug in sample application

Using gem 'jquery-turbolinks' from this solution doest work with turbolinks 5

So how can i handle this problem ?

Community
  • 1
  • 1
Emmanuel Mtali
  • 2,242
  • 17
  • 38

2 Answers2

1

You need to destroy it before page navigation:

$(document).on('turbolinks:before-cache', function() {
  // you will need to save current state (score, etc) before
  // doing this and load it during turbolinks:load
  $('#rating-form').raty('destroy')
});
nanaya
  • 450
  • 4
  • 5
0

I think what you want is load event instead.

$(window).load(function() {

  $('#rating-form').raty({

    path: '/assets/',
    scoreName: 'review[rating]', 
    score: function(){
        return 0
    },


  });

});

This is because turbolinks:visit is triggered after every visit (including back and forward), whereas window.onLoad is triggered only after initial page load (which is only triggered right after you click the link (as it sends an AJAX request, and that is the only time when onLoad is called after AJAX response has been loaded, therefore not including back and forward, as back and forward do not actually send a request when turbolinks-enabled).

turbolinks:visit works most of the time (only if the function defined you have there is idempotent of each page change, i.e. you don't add/remove DOM elements or update JS history). But since what .raty(...) function does is it appends (5 images + hidden input field) then your code above basically continuously appends these into #rating-form

Jay-Ar Polidario
  • 6,018
  • 11
  • 25