Akshay Rawat Akshay Rawat - 1 year ago 60
HTML Question

Rails3 Sprockets JS concatenation: Best practice to avoid JS conflicts

Lets say there are two pages with two different html elements which have the same name

<select id='collection_select'></select>

<select id='collection_select'></select>

and there is a javascript function which is only to be applied to


Becase Rails concatenates all JS assets, this function will now also apply to
. Is there a Rails/Sprockets/JS best practice to structure and namespace JS assets in a particular way so that the scope of the JS is limited to a particular page.

Answer Source

This blog post presents a good way of going this: http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution

To summarize it involves

  1. Putting a data-controller attribute on the <body> tag.
  2. Scoping all the JS in a namespace.
  3. A JS Util then matches and loads the JS in the JS namespace for the data-controller by convention.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download