I have a coffescript file inside the javascript folder and being inside this folder, rails automatically adds it to all the views, but I want that file to be used only in a single view because if it is added to the other views you can alter them .
1 Answer
This is a relatively common problem, but there are a few things you can do to only render that javascript on a certain page.
Javascript module pattern
Using the module pattern, you'll want to wrap most of your javascript in anonymous closures like so (in coffeescript):
do ->
# ... all vars and functions are in this scope only
# still maintains access to all globals
return
The code inside the closures that you want to execute can be wrapped inside an object like this:
(($) ->
myObj = myFunc: (param) ->
# do stuff ...
return
$('selector').click ->
myObj.myFunc()
return
return
) jQuery
So the code you want to execute is wrapped inside a function in an object, and then you can call that object when an event has fired. If the code you want to run in a single view is dependent only on user interactions like clicks, hovers, and other events, you can do something like this.
Body css classes
In rails, you can add controller and action classes to your body tag. By doing this, you can use javascript to target the css class of the body and then either execute some code or not based on the class of the current view. It would look kind of like this:
In application.html.erb
<body class = "<%= controller_name %> <%= action_name %>"
Let's say that you want to execute some coffeescript for the new action of your articles controller, then in your coffeescript file:
if $('body').hasClass('articles') and $('body').hasClass('new')
# do stuff for the articles#new
else
Paloma gem
You could check out the paloma gem, but I don't think the gem is actively maintained anymore.
I hope that helps!