mercredi 29 mars 2017

run scripts if on certain page - rails

Would it be a bad idea to run an if statement on each page load to check whether or not I should run a script. For example I have a really long javascript file that only needs to be run when using forms. But currently in each of my files I have included the document.addEventListener("turbolinks:load", function() which means it runs on every page load.

In my script I am tempted to write an if statement at the beginning of the file like so:

document.addEventListener("turbolinks:load", function() {
  controller = $('body').data('controller')
  action = $('body').data('action')
  if controller == foo && action == bar 
    runScripts();
  else
    return;
  function runscripts() {
    ...

I'm still somewhat new to using javascript with rails so I don't know of another way. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire