Javascript Rails:在`.js.erb`文件中运行`.application.js`函数
如何在Javascript Rails:在`.js.erb`文件中运行`.application.js`函数,javascript,jquery,ruby-on-rails,erb,Javascript,Jquery,Ruby On Rails,Erb,如何在.js.erb文件中运行application.js中的函数?我不想重复上述函数 app/assets/javascripts/application.js $(document).on('pagecontainershow', function() { var someFunction = function() { function someOtherFunction() { console.log('Hello world') } }(); });
.js.erb
文件中运行application.js
中的函数?我不想重复上述函数
app/assets/javascripts/application.js
$(document).on('pagecontainershow', function() {
var someFunction = function() {
function someOtherFunction() {
console.log('Hello world')
}
}();
});
//= require jquery
//= require jquery_ujs
//= require functions
//= require_tree .
app/views/articles/create.js.erb
<% unless @article.errors.any? %>
someFunction.someOtherFunction();
<% end %>
someFunction.someOtherFunction();
rails创建的默认应用程序.js
中有一条注释
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
我可以处理这个问题的方法是将代码移动到另一个js文件,比如说functions.js
,然后记下在application.js
中引用它们的顺序。在使用函数的任何其他文件之前,应该首先需要functions.js
。在你的情况下,你可以有
application.js
$(document).on('pagecontainershow', function() {
var someFunction = function() {
function someOtherFunction() {
console.log('Hello world')
}
}();
});
//= require jquery
//= require jquery_ujs
//= require functions
//= require_tree .
您现在应该能够在
create.js.erb
中调用该函数,正如我在评论中提到的,您要么需要分离出函数,要么需要调用包含这些函数的on change事件。试试这个:
function someotherfunction(){
console.log("Hello");
}
function somefunction(){
someotherfunction();
// your logic
}
$(document).on('pagecontainershow', function(){
somefunction();
});
<% unless @article.errors.any? %>
someFunction();
<% end %>
function someotherfunction(){
console.log(“你好”);
}
函数somefunction(){
someotherfunction();
//你的逻辑
}
$(文档).on('pagecontainershow',function(){
somefunction();
});
someFunction();
我最终使该函数成为一个全局jQuery函数,现在它工作得非常好:
这无法解决问题,因为您正在调用create方法,此时所有的js文件都已加载到您的页面中,因此顺序无关紧要。我们的函数在pagecontainershow的更改事件中,所以我认为它不会像这样。您必须调用页面更改,或者需要将其与该块分开。您通常应该避免使用全局变量和函数,特别是当您可以以更正常的方式进行更改时。退房或