How to decide which JavaScript chunk should be executed in Rails asset
pipelining
With Rails Asset Pipeline all JavaScript/CoffeeScript gets loaded into one
JavaScript file, that's fine. I need, however, to distinguish when to
execute which JavaScript in order to avoid error messages for instance
when applying jQuery code to manipulate elements, add events, etc.
One common solution is to namespace every element.
<div class="magazines ads panel">...</div>
Where the CoffeeScript file is in
app/assets/javascript/magazines/ads.js.coffee
$(".magazines.ads.panel")
What if I don't want to use namespaces like this? Currently, I just add a
conditional statement to look if the current window location path equals
the one I want:
if window.location.path == 'magazines/ads'
This can get tricky if the path gets a bit more complicated, contains REST
identifiers for the resources, etc. Is there a more formal approach to
encapsulate these requests or even automate them in a nice way?
No comments:
Post a Comment