在 Rails 3 应用程序中添加特定于页面的 JavaScript 的最佳方法?

问题描述:

Rails 3 有一些非常酷的不引人注目的 JavaScript.

Rails 3 has some unobtrusive JavaScript which is pretty cool.

但我想知道为特定页面包含额外 JavaScript 的最佳方法是什么.

But I was wondering what the best way is to include additional JavaScript for a particular page.

例如,我以前可能做过的地方:

For example, where I might have previously done:

<%= f.radio_button :rating, 'positive', :onclick => "$('some_div').show();" %>

我们现在可以用类似的东西让它不显眼

We can now make it unobtrusive with something like

<%= f.radio_button :rating, 'positive' %>

# then in some other file
$('user_rating_positive').click(function() {
  $('some_div').show();
}

所以我想我的问题是在哪里/如何包含该 JavaScript?我不想填写 application.js 文件,因为这个 JavaScript 只适用于这个视图.我应该以某种方式为每个页面包含一个自定义 JavaScript 文件,还是将其粘贴在标题查找的实例变量中?

So I guess my question is where/how to include that JavaScript? I don’t want to fill up the application.js file because this JavaScript is only applicable to this one view. Should I include a custom JavaScript file for each page somehow, or stick it in an instance variable that the header looks for?

我喜欢做的是在 content_for :head 块中包含 per-view Javascript,然后 yield 到应用程序布局中的那个块.例如

What I like to do is include the per-view Javascript in a content_for :head block and then yield to that block in your application layout. For example

如果它很短,那么:

<% content_for :head do %>
  <script type="text/javascript">
    $(function() {
      $('user_rating_positve').click(function() {
        $('some_div').show();
      }
    });
  </script>
<% end %>

或者,如果更长,则:

<% content_for :head do %>
  <script type="text/javascript">
    <%= render :partial => "my_view_javascript"
  </script>
<% end %>

然后,在您的布局文件中

Then, in your layout file

<head>
  ...
  <%= yield :head %>
</head>