jQuery autocomplete not working with Turbolinks

醉酒当歌 提交于 2019-12-24 02:16:36

问题


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?


回答1:


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.




回答2:


I recently had this problem with Rails 5 and the latest version of turbolinks(as of 8/24/17)

I had something similar. My issue was when navigating to another page withing my application and using autocomplete. it didnt work. after some research, I found that adding

$(document).addEventListener('turbolinks:load', function(){
 // your code here
}

to my

app/assets/javascripts/application.js

You can read some more about turbolinks here: turbolinks.

I hope this helps someone else.



来源:https://stackoverflow.com/questions/15958686/jquery-autocomplete-not-working-with-turbolinks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!