Arrange jQuery Ruby On Rails

3

I have an app in rails 4 and after doing the scaffolding it generates a * .js.coffee for each template, as I am not yet using coffeescript renamed to * .js and I am trying to use jQuery. The problem is that I need to trigger a process delayed by ajax after loading the page itens/show/x and did as follows

$(document).ready(function() {
  $.ajax({ 
    url:'/get_content_recommendation/' + gon.item_id + '.js',
    type:"get"
  });
});

The problem is that it is running on all pages of the app, because of <%= javascript_include_tag "application", media: "all" %> in layout before <%= yield %>

What is the best solution for separating jQuery by view, is there any gem or any good practice? Is this the best way to trigger ajax process after page loading?

    
asked by anonymous 22.08.2014 / 04:07

2 answers

2

Rails recommends using Unobtrusive Javascript , where you use selectors to manipulate the elements:

$("#id")
$(".classe")
$("table[data-table]")
// etc

So one of the ways you can base yourself on a particular element on that page:

<div id="div-especifica-desta-pagina">
  ...
</div>

And then, via jQuery:

$div_especifica = $("#div-especifica-desta-pagina");
if ($div_especifica.lenght) {

  $.ajax({ ... });

}

The code inside if will only be executed if the element is found.

An alternative would be to create a Javascript function in NomeDoControlador-NomeDaAção format:

function UsuariosIndex() {

  $.ajax({ ... });

}

And then call it via a <script> tag only on the correct page:

<script>UsuariosIndex()</script>
    
22.08.2014 / 13:18
2

One alternative is that I use a block in the layout to inject specific files of js, which will only be used in that view, you can use this way:

<% content_for :footer do %>
  <%= javascript_include_tag 'itens_load' %>  
<% end %>

Just that your layout has a <%= yield :footer %> block so you can include the specific js in the block. It's worth remembering that you should add your specific assets to the precompile of your config/production.rb file, in the example it would be: config.assets.precompile += %w( itens_load.js )

    
22.08.2014 / 13:48