0

If we have:

#app/assets/javascripts/tabbed_panels.js
var new_items = function() {
 #do something
});

$(document).on("turbolinks:load", new_items);

and

#app/assets/javascripts/paginate_users.js
var new_users = function() {
 #do something
});

$(document).on("turbolinks:load", new_users);

etc

Is there a way to avoid repeating $(document).on("turbolinks:load", '#'); for every script?

coreyward
  • 77,547
  • 20
  • 137
  • 166
Timmy Von Heiss
  • 2,160
  • 17
  • 39

1 Answers1

1

I don't think queuing multiple functions for the same event is a bad pattern or violates DRY principles, but you could encapsulate the behavior in a single function to avoid having your various modules know about the load behavior of Turbolinks:

var initialize = function(callback) {
  $(document).on('turbolinks:load', callback);
}

# later...
initialize(new_users);
coreyward
  • 77,547
  • 20
  • 137
  • 166
  • Thanks. Do you know if there is a way I can do something like this with a ruby method so I can dry up all the `data: {turbolinks: false}` in my `<%= link_to ... %>` https://stackoverflow.com/questions/41336325/is-there-a-way-around-writing-data-turbolinks-false-a-zillion-times-is-turb – Timmy Von Heiss Dec 30 '16 at 05:30
  • @TimmyVonHeiss Ideally you're not doing much/any of that, but you can always either override `link_to` or create a separate helper that wraps `link_to` or its `options` argument (e.g. `link_to foo, foo_path(@foo), default_link_options` where you've defined `default_link_options` elsewhere). – coreyward Dec 30 '16 at 08:44
  • It seems like very few of my jquery scripts work correctly when the page is opened through a `link_to` unless I have `data: {turbolinks: false}` – Timmy Von Heiss Dec 30 '16 at 16:06
  • @TimmyVonHeiss Are your JS include tags in the body? If so, that's probably what's causing issues for you. – coreyward Dec 30 '16 at 17:15
  • My JS include tags are in the head: `<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>` – Timmy Von Heiss Dec 30 '16 at 20:16
  • 1
    fwiw, i figured out that what i thought were turbolinks problems was really problems related to a scroll script that paginates new pages that i wrote.. it was carrying over to other pages. i fixed it. it was not related to turbolinks. – Timmy Von Heiss Jan 03 '17 at 06:58