I have a problems with javascripts assets in Ruby on Rails. Descripttion: I have two files in app/assets/javascript folder.
- "constans.js" include a constant array "var FEATURES = new Array["A","B","C"]"
- "route.js.erb" <%= FEATURES[1] %>
Now , I'm implementing my function in "route.js.erb" but I can't access the "FEATURES" array ?
I searched on Google but can't not find the solution.
So, anybody can help me? Thanks! ( my first question in stack overflow , sorry for my bad english)
use
window.FEATURES = new Array["A","B","C"]"
in constants.js
and make sure that the constants.js is being loaded.
There are several important factors:
- Scoping of the variable
- Calling the variable in ERB
Scope
First, you need to ensure your variable is scoped globally. To do this, you've declared the variable in constants.js
, so you need to ensure this is called before the routes.js.erb
file. You should also take @user3243476
's advice & append it to the window
object:
#js/constants.js
window.FEATURES = new Array["A","B","C"]
ERB
Secondly, you're calling routes.js.erb
(which is fine), but inside you're calling <%= FEATURES["1"] %>
. Problem. This is calling a Rails constant, not the JS one. This means even if your variable's scope is global, you're trying to call one which doesn't exist.
You'll need to do this:
#js/routes.js.erb
alert(FEATURES["1"]);
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.