Search code examples
jqueryjquery-uiturbolinks

jQuery autocomplete not working with Turbolinks


I'm using Rails 4. This snippet from my shared.js.coffee works fine without turbolinks:

jQuery ->
  $('input.autocomplete,textarea.autocomplete').each (index, item) =>
    sel = $(item)
    sel.autocomplete
      source: sel.data('autocomplete-source')
      minLength: 1

But when I use Turbolinks, it only works on a page refresh. It does not work after navigating through the site.

I've read Rails 4, Turbolinks, and Delegated Event Handling in jQuery, so I have some idea of what is going wrong, but I'm not yet sure how to fix the problem.

And, a related question: can anyone comment definitely if the jQuery UI autocomplete plugin -- or for that matter, plugins in general -- is/are designed to work with Turbolinks?


Solution

  • Use jQuery Turbolinks.

    "if you have a large codebase with lots of $(el).bind(...) Turbolinks will surprise you. Most part of your JavaScripts will stop working in usual way. It's because the nodes on which you bind events no longer exist."

    Usage:

    # Gemfile:
    gem 'jquery-turbolinks'
    
    # JavaScript manifest file:
    //= require jquery.turbolinks
    

    Perhaps, at some point, the jQuery $.widget function will offer an option to bind differently, but until then, this works. No other changes to the Javascript are required.