How do I associate a CoffeeScript file with a view?
Just installed rails 3.1 rc1 and am trying to grok the best way to manage javascript with the new asset pipeline By default all coffeescript is compiled into a single application.js file, this is a good thing.
Each seperate coffee script file is appended to the js file and wrapped in an anonymous function which is executed via the call method A common scenario would be to use some jquery to turn various forms into ajax forms, update UI, etc...
Many of these scripts will be specific to a controller o开发者_StackOverflow中文版r action, I am trying to grok the 'conventional' way to handle this, since everything is wrapped in an anonymous function how do I only execute just the code for a particular controller / action, by default all of the anonymous functions are being executed
I did play around with some hacks where I load the controller and action name into js variables and then in coffeescript check those to conditionally run code, I don't like that very much
my initial thought was that each coffee file would contain a js namespace/object and I would call the specific ones from the view, going to spike this using the default_bare = true configuration
see How can I use option "--bare" in Rails 3.1 for CoffeeScript?
EDIT
Looking around some more: this looks like it might be the correct approach - "Can't find variable" error with Rails 3.1 and Coffeescript
There are two common approaches:
Make behavior conditional on the presence of a particular element. For instance, code to run a signup sheet should be prefaced with something like
if $('#signup').length > 0
Make behavior conditional on a class on the
body
element. You can set the body class using ERB. This is often desirable for stylesheets as well. The code would be something likeif $('body').hasClass 'user'
gistyle is a simple gem that helps you running action-specific javascript codes.
By following its setup, you set some data attributes in your body element, representing the current controller and action names. Then it will only call that action when the corresponding view is loaded.
精彩评论