jquery - Rails page-specific JavaScript: What's the best practice? -



jquery - Rails page-specific JavaScript: What's the best practice? -

anyone knows rails asset pipeline knows default behavior javascript files included in manifest rolled 1 large, awkward, unfortunate ball.

all javascript -> application.js

what means if have javascript file foo.js, activate not pages reached controller foo, every other page.

this easy work around, wonder best way it.

i had application.html.erb pass current controller , action javascript in app using javascript tag.

<%= javascript_tag %> window.givencontroller = "<%= controller_name %>"; window.givenaction = "<%= action_name %>"; <% end %>

in js files, surround page specific code on controller named files sort of if statement ensure ran on pages.

if(givencontroller == "foo" && givenaction == "bar"){ dostuff(); }

my boss contends creates unnecessary variables , suggested instead utilize if statement pointing specific jq elements on page:

if($("#some-element-in-foo").length > 0){ dostuff(); }

while i'm expected follow boss's directions, i'm conflicted how should approach in future apps. think approach more expressive , flexible 1 suggested, might missing critical flaws.

how sense these 2 practices, both , respect each other, , why? might improve ways of solving same problem?

it's matter of preference:

take care of elements nowadays in dom regardless of controller/action. applying javascript events navigation elements nowadays through entire application.

do more targeted javascript logic based on controller/action. adding click event particular button shows in controller , action.

you have need solve both cases in application.

a different approach, more on lines of yours, add together controller_name , action_name classes on body tag <body class="<%= controller_name %> <%= action_name %>">

then within document ready check presence of class: $("body").hasclass("mycontroller");

this eliminate complaint boss has unnecessary variables.

javascript jquery ruby-on-rails

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -