How to link a CoffeeScript file to a view?

Just installed rails 3.1 rc1 and trying to find the best way to control javascript using the new pipeline By default, all coffeescript are compiled into a single application.js file, which is good.

Each individual coffee script file is added to the js file and verified with an anonymous function that is executed using the invocation method. A typical script would be to use some jquery to turn various forms into ajax forms, update the user interface, etc.

Many of these scripts will be specific to the controller or action, I’m trying to understand the “usual” way to deal with it, since everything is wrapped with an anonymous function, how can I execute only the code for a specific controller / action, by default all anonymous functions are executed

I played with some hacks, where I loaded the controller and action name into js variables, and then in coffeescript check those to conditionally run the code, I don’t really like it

My initial thought was that each coffee file would contain js namespace / object, and I would name specific ones from the view, going to hiss this using the default_bare = true configuration

see How to use the - bare parameter in Rails 3.1 for CoffeeScript?

EDIT

Looking back at a few: it looks like this might be the right approach - “Unable to find variable” error with Rails 3.1 and Coffeescript

+16
coffeescript
May 26 '11 at 3:00 a.m.
source share
2 answers

There are two general approaches:

  • Make the behavior conditional on the presence of a specific element. For example, the code to start the registration sheet should be preceded by something like

    if $('#signup').length > 0

  • Make the behavior conditional for the class in the body element. You can set the body class using ERB. This is often desirable for style sheets. The code will be something like

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

+22
May 26 '11 at 3:27
source share

gistyle is a simple stone that helps you run javascript codes for specific actions.

Following its configuration, you set some data attributes in your body element, representing the current controller and action names. Then it will call this action only when loading the corresponding view.

0
Feb 11 '14 at 4:36
source share



All Articles