简体   繁体   中英

How should I handle event listeners on page elements when using Turbolinks 5 in Rails?

According to the Turbolinks readme , we shouldn't be setting event listeners directly on page elements when using turbolinks:load :

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.

That being the case, sometimes you need to set listeners on individuals elements. What's the recommended way to do that? Use a different Turbolinks event? Something else?

If the event is triggered by the user (click, keyup, etc.) then you can simply use

$(document).on('click', '#id', function(e) {......

It works fine since it is bind to the document not to a class/id that can change or get removed. Use this when you can.

If you need something on page load, then you have to use turbolinks:load like below. You need this since with turbolinks you don't do real full page reload, but you have to tell somehow the browser, that you are on different page already.

$(document).on('turbolinks:load', function() {
  $('.class').geocomplete();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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