Akshay Rawat Akshay Rawat - 4 months ago 8
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

a.html
<select id='collection_select'></select>


b.html
<select id='collection_select'></select>


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


a.js
$(function(){
$('#collection_select').change(function(){
....
})
})


Becase Rails concatenates all JS assets, this function will now also apply to
b.html
. 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

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.

Cheers

Comments