简体   繁体   English

如何在Rails应用程序中使用js.erb

[英]How to use js.erb in rails app

I have tried everything I can find to use a js.erb file, because I need to use ruby along with my js. 我已经尝试过使用js.erb文件找到的所有内容,因为我需要在我的js中使用ruby。

I know it is not the code, because I have the same thing in application.js, and it works fine. 我知道这不是代码,因为我在application.js中有相同的东西,并且工作正常。

Model: topics 型号:主题

I've tried adding topics.js.erb to views/topics/ I've tried a partial _index.js.erb, and rendering it - I see it loading, but it is not executing. 我尝试将topic.js.erb添加到views / topics /中,并且尝试了部分_index.js.erb并进行渲染-我看到它正在加载,但未执行。

In both files, I have : 在两个文件中,我都有:

$(document).ready(function()    {
    console.log('something');
})

Is there something obvious I'm missing here? 有什么明显的我想念的地方吗? Thanks! 谢谢!

Ok, I think I understand your question now. 好吧,我想我现在已经明白你的问题了。 You have some index action in controller, index.html.erb view and index.js.erb and you want to run javascript from index.js.erb after rendering index.html.erb . 您在控制器, index.html.erb视图和index.js.erb有一些索引操作,并且您希望在渲染index.html.erb之后从index.js.erb运行javascript。 It won't work, js.erb views are used for something else. 它无法正常工作, js.erb视图用于其他用途。 To run your javascript code only when index action is rendered you can just put this javascript code inside index.html.erb view. 要仅在呈现索引动作时运行您的javascript代码,您只需将此javascript代码放入index.html.erb视图中即可。 Or you can put this code in your application.js file and add additional conditions, so it will run only for index action. 或者,您可以将此代码放在application.js文件中并添加其他条件,因此它将仅针对索引操作运行。

There is no Rails way solution to this, but you can try something like this: 目前还没有Rails方式的解决方案,但是您可以尝试执行以下操作:

index.html.erb: index.html.erb:

# ... your code here

<script type="text/javascript">
  window.railsView = "controller_name#index";
</script>

application.js: application.js:

$(document).ready(function() {
  if (window.railsView == "controller_name#index") {
    console.log("something");
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM