Javascript DOM events before and after Turbolinks cache

荒凉一梦 提交于 2019-12-07 00:46:31

I think the problem here is that you are binding to two events: turbolinks:load and $(document).ready().

Turbolinks does not discard event listeners on the document so you can safely bind click handlers to it and they will be called scross page loads. From the Turbolinks documentation:

When possible, avoid using the turbolinks:load event to add event listeners directly to elements on the page body. Instead, consider using event delegation to register event listeners once on document or window.

With this in mind, you can do:

$(document).on 'click', "button#show-hide", (e) ->
  e.preventDefault()

How about you simply take the click event out of the 'turbolinks:load' and

'turbolinks:before-visit' context.

or If the button is added dynamically in the DOM, what you can do is attach a click handler to body and on click determine which element was clicked and proceed accordingly.

$('body').on('click','button#show-hide',function(){

});

In coffee script, you can do

$('body').on('click', 'button#show-hide', ( ->

));

UPDATE

From the answer on Rails, javascript not loading after clicking through link_to helper

If you want your click handlers to work on page:change and as well as on ready event you can do,

var ready = function() {
    // bind click handlers to DOM elements here
};

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