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?
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 forturbolinks:loadmight 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 withdocument.removeElementListenertoo.)Option 2. Namespace your event. jQuery supports customised event names, so with this approach you don't need to reference the handler.