Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 or 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

like image 895
house9 Avatar asked May 26 '11 03:05

house9


People also ask

What can you do with CoffeeScript?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

How do I use CoffeeScript in HTML?

If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.

Should you use CoffeeScript?

CoffeeScript is something that makes even good JavaScript code better. CoffeeScript compiled code can do everything that natively written JavaScript code can, only the code produced by using CoffeeScript is way shorter, and much easier to read.


1 Answers

There are two common approaches:

  1. 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

  2. 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 like

    if $('body').hasClass 'user'

like image 52
Trevor Burnham Avatar answered Nov 05 '22 20:11

Trevor Burnham