4

When creating event handlers in a Rails/Turbolinks-enabled app, is it best to delegate to document.body or document? Is there an accepted convention?

I've read that delegating to document is slightly less performant. However, it does allow you to avoid registering ready callbacks throughout your javascript codebase. Assume my scripts are in the <head> as is recommended for Turbolinks.

An example using jQuery (although the question isn't really about using jQuery):

$(document).on('click', 'selector', callback);

// versus

$(document).ready(function() {
  $(document.body).on('click', 'selector', callback);
});
jthomas
  • 858
  • 6
  • 19
  • This post might help: http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links – MrYoshiji Aug 18 '15 at 14:57
  • Yeah, I saw this one. If my question was "how can I make my existing js work with turbolinks?" that answer would be acceptable. I'm more interested in how you would implement it if you had no legacy. – jthomas Aug 18 '15 at 15:09
  • Using `$(document).ready` with Turbolinks willl not work everytime. So you can either listen on events on the `$(document)` directly or use `$(document).on('page:load', callback)`. Therefore `$(document).ready` is not a valid option for you. – MrYoshiji Aug 18 '15 at 15:42
  • Also I don't think that listening on events this way `$(document).on('click', 'selector', callback);` will work if the HTML element is not yet in the page but loaded later with Turbolinks – MrYoshiji Aug 18 '15 at 15:44
  • 1
    @MrYoshiji Yes it does, that's the point of event delegation. The event is not bound to 'selector' but to document, and whenever the callback is executed the event delegation checks if the original element causing the event corresponds to the given 'selector'. – sudoremo Feb 20 '19 at 08:50

0 Answers0