using jQuery's delegated event on() within every turbolinks page:load

╄→尐↘猪︶ㄣ 提交于 2019-12-08 13:19:29

Adding event handlers to the document on document page:load will as you have read create duplicate handlers. Try running the snipped below:

(click Trigger page:load several times before Click me!)

$(document).on('page:load', function(){
    $(document).on('click', '#test', function(){
      $("#log").append('<li>clicked!</li>');
    });
});
$("#page_load").on('click', function(){
  $(document).trigger('page:load');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="page_load">Trigger page:load</button>
<button id="test">Click me!</button>
<ul id="log"></ul>

Turbolinks basically works by loading pages via Ajax instead and replacing the document contents.

It does try to clean up event handlers when it removes the old page from the DOM - but since your handler is bound to the document it is not removed.

You can relatively safely apply handlers to DOM elements such as the body instead since turbolinks guts out the document and replaces the contents.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!