【问题标题】:Rails: Running a function from `application.js` inside a `.js.erb` fileRails:在“.js.erb”文件中从“application.js”运行一个函数
【发布时间】:2014-07-08 17:45:18
【问题描述】:

如何在.js.erb 文件中运行application.js 中的函数?我宁愿不必复制所述函数。

app/assets/javascripts/application.js

$(document).on('pagecontainershow', function() {
  var someFunction = function() {
    function someOtherFunction() {
      console.log('Hello world')
    }
  }();
});

app/views/articles/create.js.erb

<% unless @article.errors.any? %>
  someFunction.someOtherFunction();
<% end %>

【问题讨论】:

  • 您的函数在 pagecontainershow 的更改事件中,所以我认为它不会像这样。您将不得不调用您的页面更改或需要将其与该块分开

标签: javascript jquery ruby-on-rails erb


【解决方案1】:

rails 创建的默认application.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 应该在使用这些功能的任何其他文件之前首先被要求。在你的情况下,你可以有类似的东西

应用程序.js

//= require jquery
//= require jquery_ujs
//= require functions
//= require_tree .

您现在应该可以在 create.js.erb 中调用该函数

【讨论】:

  • 这不会解决这里的问题,因为你正在调用 create 方法,那时所有的 js 文件都已经加载到你的页面中,所以顺序无关紧要
【解决方案2】:

正如我在评论中提到的那样你要么需要分离出你的函数,要么你需要调用包含这些函数的 on change 事件。试试这个:

function someotherfunction(){
  console.log("Hello");
}    

function somefunction(){
  someotherfunction();
  // your logic 
}

$(document).on('pagecontainershow', function(){
  somefunction();
});

<% unless @article.errors.any? %>
  someFunction();
<% end %>

【讨论】:

    【解决方案3】:

    我最终使该函数成为一个全局 jQuery 函数,现在它工作得很好:

    global jquery function

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-08
    • 2012-07-19
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多