Using the turbolinks:load event only once for a particular page?
Asked Answered
J

1

6

I've got some code that I want to run only on one page of my app, so in my HTML I'm using the following inline JS:

<script>
  $(document).on('turbolinks:load', function() {
    console.log("Ground control to major tom?")
  });
</script>

However, then when the user navigates away from that page - that code is still running on every subsequent visit.

How can I use the turbolinks:load event only for a particular page?

Do I need to somehow 'tear down' that event handler? How would I prevent that from affecting any other turbolinks:load events that I may have?

Jaimie answered 2/4, 2020 at 17:48 Comment(0)
K
6

First of all, check if you need to run this code on turbolinks:load—you might not need to! <script>s included at the bottom of the page will have access to all DOM elements, so listening for turbolinks:load might not be necessary.

If you are sure you need to handle turbolinks:load, to tear down your handler, you have a couple of options.

Option 1. Used a named function, then reference that when calling off. (This approach would be compatible with document.removeElementListener too.)

;(function () {
  function onLoad () { console.log("Ground control to major tom?") }

  $(document).on('turbolinks:load', onLoad);

  $(document).on('turbolinks:before-render', function() {
    $(document).off('turbolinks:load', onLoad);
  });
})()

Option 2. Namespace your event. jQuery supports customised event names, so with this approach you don't need to reference the handler.

$(document).on('turbolinks:load.my-namespace', function() {
  console.log("Ground control to major tom?")
});

$(document).on('turbolinks:before-render', function() {
  $(document).off('turbolinks:load.my-namespace');
});
Kirghiz answered 21/5, 2020 at 16:56 Comment(1)
Option 2 is exactly what I needed. ThanksMuddy

© 2022 - 2024 — McMap. All rights reserved.