Javascript DOM events before and after Turbolinks

2019-08-21 08:35发布

Here I have:

$(document).on 'turbolinks:load', ->
  console.log "page has loaded!"
  $ ->
    $("button#show-hide").click (e) ->
      e.preventDefault()

which makes my click event available only after Turbolinks caches page. I can do $(document).on 'turbolinks:before-visit which will make event available only before Turbolinks caches. How should I make event available at all times?

2条回答
Deceive 欺骗
2楼-- · 2019-08-21 09:08

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()
查看更多
冷血范
3楼-- · 2019-08-21 09:15

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);
查看更多
登录 后发表回答