简体   繁体   中英

Confused about how to use vanilla JavaScript with Ruby on Rails

I have two views, one called dashboard and the other called home , both have their respective index.htm.erb files. The corresponding JavaScript files in the assets/javascripts folder do not seem to map to these views. For example, when I run an alert in home.js and then navigate to dashboard.html.erb the alert still runs.

How do I remedy this to get the functionality I am looking for?

I am confused as to how to write page specific raw JavaScript in Rails.

Edit : I could use the public folder but I had some ancillary issues with that and hence why I started using the files in the assets folder.

One of Rails' "opinions" about javascript is that it should be all concatenated into a single file ( application.js ), minified, and served to the client. This is an effort to minimize the number of requests the client needs to make when accessing your application (the goal is to have only three, one for your html, one for css, and one for javascript [excluding whatever images may be on the page.])

If you look in your application.js, you'll see a note saying that it is a 'manifest' file, and a line that looks like

require_tree .

Which says "load every javascript file in this folder into this file"

In order to load up some page-specific javascript, you'd need to

  • put a separate javascript file into app/assets/javascripts [call it custom.js, say]
  • stub out loading that file into the application manifest by writing stub custom in application.js
  • Include the custom javascript manually in your view (or, more better probably, a layout which renders your view): <%= javascript_include_tag 'custom' %>

However, I'd encourage you to look at whether you really need to separate this javascript, or whether it's a problem that can be solved by simply localizing your script to the page(s) it's intended for, which will keep the same functionality and keep your loads times ever-so-slightly faster.

$('body.some_custom_class').ready(function() { alert('I'm running on this page!'); });

you can use content_for in your layout

app/views/layouts/application.html.erb

<html>
  <head>
     <title> ...</title>
     ....
     <%= yield :javascript %>
     ....
    </head>
    ....
 </html>

and on your view app/views/home.html.erb

 <% content_for :javascript do %>
    <%= javascript_include_tag 'home' %>
 <% end %>
 other view content

you would also need to look at application.js and remove the //= require tree . line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM