Rails, turbolinks and inline javascript. How to avoid duplicate event handlers?
<p>I have read many posts on the internet, but in the end I still haven't found a nice solution to deal with Turbolinks + inline scripts.</p>

<p>Turbolinks does give a nice feeling and I don't really want to stop using it, but in some cases I have a hard time debugging duplicate event handlers.</p>

<p>I have some views with inline javascript : I actually prefer having the (small) javascript codes near the element(s) that are interacted with, saving only big javascripts functions for app.js.</p>

<p>So imagine I have a search page with several filters, but only on that specific page. When the user changes the search filters, it is supposed to GET (using remote/AJAX) the new results. The easiest way was to introduce </p>

<pre><code>$(document).on('ready turbolinks:load', function() {
  // Submit on every change
  $('#myform input').change(function() {
    $('#myform').submit()
  }
})
</code></pre>

<p>When navigating with turbolinks and going back to the search page, I naturally end up with several duplicate bindings on every select, causing multiple form submits.</p>

<p>I have tried adding</p>

<pre><code>$('#sidebar-search input').unbind()
</code></pre>

<p>Just before the <code>.change()</code> line but it doesn't seem to work, and for some reason the form is still posted several times : once with AJAX, several other duplicates (that thankfully are cancelled) and another non-remote request (my server replies with HTML).</p>

<p>Using turbolinks 5</p>

<p><a href="https://i.stack.imgur.com/6wfbJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6wfbJ.png" alt="enter image description here"></a></p>