Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

ruby on rails 3.1 - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...