共享JS(咖啡)在Rails [英] Shared JS (Coffee) in Rails
问题描述
如果我想在 app / assets / javascript 下的不同文件之间共享一些JavaScript函数,那么最好的方式是组织目录结构?
If I want to share some JavaScript function between different files under app/assets/javascript what would be the best way to I organise the directory structure?
假设我有 shared.js.coffee
Let's say I have shared.js.coffee
sharedFunction = ->
'Hello '
现在,我如何在其他地方使用它?像这里一样,在 welcome.js.coffee
Now, how can I use it in some other place? Like here, in welcome.js.coffee
welcome = (name) ->
sharedFunction() + name
如何制作 shared.js.cofee 始终首先加载?
我试图将其放在 application.js ,但它不会改变任何东西。似乎已共享文件加载时间过长,欢迎设法开始执行,并注意到没有定义sharedFunction。
I tried to put it in the very beginning of application.js, but it doesn't change anything. Seems shared file loading too long, and welcome manages to start executing and notice that sharedFunction is not defined.
推荐答案
在 application.js
中,加载共享第一个:
In application.js
, load shared first:
//= require shared
//rest of code
如果有必要,可以在全局范围内访问您的变量:
and in shared, if its that necessary, make your variable accessible globally:
@sharedFunction = ->
'Hello '
注意它的坏习惯也有这样的全局变量,将它们保存在命名空间中。
Notice its a bad practice too have such global variables, at least try to keep them in namespaces.
这篇关于共享JS(咖啡)在Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!