views:

36

answers:

1

Rails 3 has some unobtrusive javascript which is pretty cool.

But I was wondering what the best way is to include additional JS 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_positve').click(function() {
  $('some_div).show();
}

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

+1  A: 

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

If it's pretty short then:

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

or, if longer, then:

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

Then, in your layout file

<head>
  ...
  <%= yield :head %>
</head>
bjg
I like it - thanks!
Brian Armstrong