4

With Rails 3+ and the asset pipeline my understanding is that all the javascript files under assets/javascripts get automatically included and compiled into one js file if you specify

require_tree . 

in application.js.

What is the best practice regarding dealing with javascript that is specific to a controller/view? For example suppose I have a controller/view 'Houses' and I want to validate the houses form using the jquery form validation plugin, to do that I have placed the following code in my houses.js file

$(document).ready(function(){
  $("#new_house_form").validate();
});

which is fine but the problem is that when I visit another page (say /owners), it tries to validate the houses form and I get an error message in the javascript console. Ofcourse I could just check if the form exists on the current page or not and only then call the validator but that seems a little unclean to me esp if I have a lot of controller specific code in .ready.

My solution to work around this has been to create a folder assets/javascripts/global and in application.js

 require_tree ./global //instead of require_tree .

and move all the other js files except for houses.js in it. Then I manually include houses.js whenever the user accesses /houses/new or /houses/edit

Is this practice acceptable? If not what is considered to be the best practice to deal with these situations?

1

1 Answer 1

0

Usually I just let all the js get loaded and check if the element exists before calling any method on it.

$(document).ready(function(){
  if($("#new_house_form").length > 0){
    $("#new_house_form").validate();
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

The problem with this is that if you have a lot of controller/view specific code (not just for forms) in your javascript then you are doing a lot of this kind of error checking. It's fine for the odd validation here and there but it gets pretty ugly as your javascript grows. I was hoping there would be a cleaner way to deal with this than manual error checks or the method I described in the question.
Yes, it's true that with this method you'll have a lot of error checking in your javascript. It's a quick fix for you problem. If you want a cleaner solution check the link that @agmin posted on his comment. Looks like a nice solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.