简体   繁体   English

Turbolinks 5 [正确加载Javascript]

[英]Turbolinks 5 [Loading Javascript Properly]

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 使用加载我的js代码

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

doesn't work until full page load( as i espect). 不工作 ,直到满页面加载(如我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 使用解决方案中的gem'jquery -turbolinks' 不适用于turbolinks 5

So how can i handle this problem ? 那么我该如何处理这个问题呢?

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')
});

I think what you want is load event instead. 我认为您想要的是load事件。

$(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在每次visit (包括后退和前进)后触发,而window.onLoad仅在初始页面加载后才触发(仅在单击链接后立即触发(因为它发送AJAX请求,并且是在加载AJAX响应之后调用onLoad的唯一时间,因此不包括back and forward,因为启用Turbolinks时back and forward实际上并不发送请求)。

turbolinks:visit works most of the time (only if the function defined you have there is idempotent of each page change, ie you don't add/remove DOM elements or update JS history). turbolinks:visit在大多数时间都是有效的(仅当您定义的函数具有每次页面更改的幂等性时,即,您不添加/删除DOM元素或更新JS历史记录)。 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 但是由于.raty(...)函数的作用是将其追加(5张图片+隐藏的输入字段),因此您上面的代码基本上将这些连续地追加到#rating-form

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM