Pregunta

My application structure looks like this

myapp
  app/assets/javascripts/admin/admin.js
  app/controllers/admin/admin_controller.rb
  app/views/admin/new.html.haml
  app/views/admin/new.js.haml

I am using some ajax functions to render particular content in my form. The actions specified in new.js.haml which is triggered when call was in js format. I also have some other scripts in my admin.js file which is not including after this ajax call. When I copy and paste the script in new.js.haml, all works fine. But I don't want to have redundant scripts in my app. How to re-factor this?

¿Fue útil?

Solución

You are correct in that it is not a good idea to duplicate your code. As for your question of where to put the javascript files, it doesn't really matter (though typically, for reasons beyond the scope of your question, they reside in app/assets/javascripts).

The important thing is that the javascript functions you're calling from new.js.haml have actually been defined, which means the javascript file must be loaded. This can be done by including the javascript file in the of your layout, like this:

<%= javascript_include_tag "admin/admin" %>

Define functions in your main javascript file:

// admin.js

var testFunc = function() {
  console.log('this is a test!')
};

then call the function in your new.js file:

// new.js

testFunc();

No need to redefine your functions or variables.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top