MKK
MKK

Reputation: 2753

How can I only show the JavaScript in particular controller and method?

I have many models. Now I like to show the JavaScript to only the particular controller and method.

For example, if I had code like this and want to show it only in communities/show Should I paste this in the head of view/communities/show.html.erb?
or is there smarter way to manage this kind of things? Obviously it looks ugly if I put it in the head of show file because JavaScript always should be placed within < head> tag.

<%= javascript_tag do %>
    jQuery(document).ready(function () {
        refreshPartial();
        setInterval(refreshPartial, 5000)
    });


    function refreshPartial() {
      $.ajax({
        url: "<%= community_path %>/refresh_part",
        type: "GET",
        dataType: "script",
      });
    }
<% end %>

Upvotes: 0

Views: 97

Answers (2)

Raghvendra Parashar
Raghvendra Parashar

Reputation: 4053

communities.js

jQuery(document).ready(function () {
  refreshPartial();
  setInterval(refreshPartial, 5000)
});


function refreshPartial() {
  $.ajax({
    url: "community/refresh_part",
    type: "GET",
    dataType: "script",
  });
}

view/communities/show.html.erb

<%- content_for(:head) do -%>
<%= javascript_include_tag :communities.js -%>
<%- end -%>

communities_layout

<head>
<title>Merry Christmas!</title>
<%= yield(:head) -%>
</head>

Upvotes: 4

Nishant
Nishant

Reputation: 3005

There are a couple of ways to do that

  1. top of your show.html.erb:

    <% content_for :javascript_includes do %>
    <%= javascript_include_tag "forms.js" %>   
    <% end %>
    

    Also refer to this answer

  2. Where do you put page specific JavaScript code and take a look at How Asset Pipeline works

Upvotes: 1

Related Questions