Application.js.coffee rails

2019-09-12 20:03发布

问题:

I am trying to do an autocomplete from jQuery, however the code that I have is in CoffeeScript. I am not to sure how to run it on my localhost server.

At first I placed it in application.js but that doesn't work, so then I created gens.js.coffee and placed the code there, but still doesn't show.

Here is the code:

jQuery ->
  $('#querysearch').autocomplete
    source: ['foo', 'food', 'four']

Here application.js is calling the file:

//= require gens
//= require jQuery.ui.datepicker
# file his actually gens.js.coffee

This is how I call application.js:

<%= javascript_include_tag "application" %>

What I am doing wrong?

回答1:

Firstly I would make sure that I have the CoffeeScript and jQuery UI gems in my Gemfile.

group :assets do
  gem 'coffee-rails'
  gem 'jquery-ui-rails'
end

Then I would make sure I was requiring these assets correctly. I think you are making mistakes here

  1. by capitalizing the Q in jquery.
  2. by requiring datepicker then trying to call autocomplete
  3. by requiring your jQuery UI library after your 'gens' file.

It should look like this

//= require jquery.ui.autocomplete
//= require gens

You can place JS code (NOT CoffeeScript) straight into the application.js file if you like or it should be ok in your gens.js.coffee file.

You could also try running your server and visiting http://localhost:3000/assets/application.js. You can look at the JS there and see if it looks correct.

I would also try to open Dev tools in the Chrome browser and look for JavaScript errors.