Anyone who knows about the Rails resource pipeline knows that the default behavior for all JavaScript files included in the manifest should be collapsed into one large, uncomfortable, failed ball.
ALL THE JAVASCRIPT -> application.js
This means that if you have a JavaScript file foo.js, it activates not only the pages that the foo controller points to, but also for every other page.
This is very easy to get around, but I wonder how best to do it.
I originally had application.html.erb pass the current controller and JavaScript action to my application using a JavaScript tag.
<%= javascript_tag do %> window.givenController = "<%= controller_name %>"; window.givenAction = "<%= action_name %>"; <% end %>
In my js files, I would then surround the page-specific code on the controller with names with this type of if statement to make sure that they only work on these pages.
if(givenController == "foo" && givenAction == "bar"){ doStuff(); }
My boss claims this creates unnecessary variables and suggests instead using an if statement pointing to specific JQ elements on the page:
if($("#some-element-in-foo").length > 0){ doStuff(); }
While I obviously should follow my boss's directions, I disagree with how I should approach this in future applications. I think my approach is more expressive and flexible than the one suggested, but I could miss some critical flaws.
How do you feel about these two practices, both on your own and in relation to each other, and why? What could be the best way to solve this problem?