2014-04-28 65 views
3

页面特定的JavaScript的正确方法我想包括这一点,例如:在一个Rails应用程序包括在Rails中

jQuery(document).ready(function($) { 
    $('#my-modal').modal(options) 
}); 

在一个特定的地方。在我的情况下,该文件被称为views/modals/mymodal.html.erb。那里,只有那里。

我不知道如何做到这一点,如果我没有把它放在所有页面上,就像我把它放在资产中一样。谢谢!

回答

1

其中一个解决方案是在插入我们的JavaScript到其自身的文件:Reference Link

例如:

//应用程序/资产/ Java脚本/ alert.js

alert("My example alert box."); 

而且包括此文件仅在我们希望它执行的视图中:

<%# app/views/page/contact.html.erb %> 
<%= javascript_include_tag "alert" %> 
<h1>Contact</h1> 
<p>This is the contact page</p> 

An d不要忘记在文件列表中选择您的新文件进行编译:

# config/environments/production.rb 
config.assets.precompile += %w(alert.js) 
1

由于JS文件要包括名为my_modal.js

  1. 将您JS文件放置assets/javascriptsassets/javascripts的某个目录中,例如application

  2. 在您的application.js中更改行//= require_tree .//= require_tree application(它可以防止在每个页面上加载my_modal.js)。

  3. 将您my_modal.jsassets/javasctripts

  4. 添加my_modal.jsconfig.assets.precompile阵列(config assets.precompile += ['my_modal.js'])在application.rb

  5. javascript_include_tag 'my_modal'在视图中要包含这个文件

你可以去Rails guides参考。

6

这些都是一些有用的技巧

#1文件JS

  • 具体的布局
  • 为JavaScript中创建文件your.js
  • 调用文件your.jsapplication.js
  • 删除//= require_tree .your.js添加到资产编译器on config/application.rbconfig.assets.precompile += %w(your.js)

#2投产特定文件非布局(不推荐)

把你的JS脚本用JavaScript代码来对mymodal.html.erb


#3使用的if..else。

将您的js脚本放入layout/yourlayout.html.erb并使用if.. else..逻辑。

例如:

<% if current_page?(yourspecific_path) %> 
    <script language="text/javascript"> 
    your javascript here .. 
    </script> 
<% end %> 

了解更多关于herecurrent_page?

或者使用request.fullpath来获取当前的完整路径

例如:

<% if request.fullpath == yourspecific_path %> 
    <script language="text/javascript"> 
    your javascript here .. 
    </script> 
<% end %> 

更多hererequest.fullpath

也可以结合使用#1和#3,如果你想脚本放入文件.js

欢呼

+0

链接不工作... – Rubyist

+0

谢谢,链接编辑。 –

+0

+1有一些新东西... – Rubyist

0

晚会晚了,但对于今天任何人来说,我想我已经想出了更好的东西。

Punchbox Gem for Rails

有了这个,你可以编写代码,如:(你也可以创建一个对象,而不是一类查看文档)

class Post { 
    controller() { 
    // Runs on every action 
    } 
    index() { 
    // Runs on just the index action 
    } 
} 

Punchbox.on('Posts', Post); 

我已经写这更深入这里:https://kierancodes.com/blog/page-specific-javascript-in-rails-4