[英]Which place is best to put my JavaScript in ROR
My application structure looks like this 我的应用程序结构如下所示
myapp
app/assets/javascripts/admin/admin.js
app/controllers/admin/admin_controller.rb
app/views/admin/new.html.haml
app/views/admin/new.js.haml
I am using some ajax functions to render particular content in my form. 我正在使用一些Ajax函数来呈现表单中的特定内容。 The actions specified in
new.js.haml
which is triggered when call was in js format. 在
new.js.haml
中指定的操作,当调用为js格式时触发。 I also have some other scripts in my admin.js
file which is not including after this ajax call. 我的
admin.js
文件中还有一些其他脚本,此ajax调用后不包含这些脚本。 When I copy and paste the script in new.js.haml, all works fine. 当我将脚本复制并粘贴到new.js.haml中时,一切正常。 But I don't want to have redundant scripts in my app.
但是我不想在我的应用程序中有多余的脚本。 How to re-factor this?
如何重构呢?
You are correct in that it is not a good idea to duplicate your code. 您是对的,因为复制代码不是一个好主意。 As for your question of where to put the javascript files, it doesn't really matter (though typically, for reasons beyond the scope of your question, they reside in
app/assets/javascripts
). 至于您将javascript文件放在何处的问题并不重要(尽管通常,出于超出您问题范围的原因,它们位于
app/assets/javascripts
)。
The important thing is that the javascript functions you're calling from new.js.haml
have actually been defined, which means the javascript file must be loaded. 重要的是,实际上已经定义了从
new.js.haml
调用的javascript函数,这意味着必须加载javascript文件。 This can be done by including the javascript file in the of your layout, like this: 可以通过在布局的中包含javascript文件来完成此操作,如下所示:
<%= javascript_include_tag "admin/admin" %>
Define functions in your main javascript file: 在您的主要javascript文件中定义函数:
// admin.js
var testFunc = function() {
console.log('this is a test!')
};
then call the function in your new.js file: 然后在new.js文件中调用该函数:
// new.js
testFunc();
No need to redefine your functions or variables. 无需重新定义函数或变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.