Organize jQuery Ruby On Rails

Asked

Viewed 500 times

3

I have an app in Rails 4 and after scaffolding it generates a *.js.coffee for each model, as I am not using coffeescript renamed to *.js and 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 I did it this way

$(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 the <%= javascript_include_tag "application", media: "all" %> in the layout before the <%= yield %>

What is the best solution to separate jQuery by view, is there any Gem or any good practice? This is the best way to fire process by ajax after page loading?

2 answers

2


Rails recommends the use of Unobtrusive Javascript, where selectors are used to manipulate the elements:

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

Thus, one of the possible ways is for you to base on a specific element of 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 within the if will only be executed if the element is found.


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

function UsuariosIndex() {

  $.ajax({ ... });

}

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

<script>UsuariosIndex()</script>
  • How nice! This way it is possible to use separate the javascript inside each . js and keep the view free of javascript. I must have $(document).ready(function() {...}); for each command, only 1 per file or it is not required?

  • @Awkward If you are calling the script tag in <head> (necessary with turbolinks), you will have to use yes, it is okay to call several times. If calling at the bottom of the page before the <body> there does not need.

2

An alternative is that I use to define a block in the layout to inject specific js files, which will only be used in that view, you can use so:

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

Just have a block in your layout <%= yield :footer %> so you can include the specific js in the block. And remember that you should add your specific Assets to the precompile of your file config/production.rb, in the example would be: config.assets.precompile += %w( itens_load.js )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.