Rails for JavaScript: what's the best practice?

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?

+6
source share
2 answers

It all depends on your preference:

  • Take care of all the elements present in dom, regardless of controller / action. Similar to using javascript events for navigation items that are present across the entire application.

  • Make more targeted controller / action based JavaScript logic. As adding a click event to a specific button that is displayed only in this controller and this action.

You will most likely need to decide for both cases in the application.

Another approach, more similar to your lines, would be to add the controller_name and the action_ name as classes in the body tag <body class="<%= controller_name %> <%= action_name %>">

Then, in your document, readiness to check for the existence of a class: $("body").hasClass("mycontroller");

This will eliminate your boss's complaint with unnecessary variables.

+4
source

There is information on how to approach this at http://railsapps.imtqy.com/rails-javascript-include-external.html#external . One suggestion in this article is to use the Paloma gem .

+2
source

Source: https://habr.com/ru/post/971096/


All Articles