最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Set of CoffeeScriptJavaScript classes and methods available to rest of Rails app - Stack Overflow

programmeradmin3浏览0评论

I'm using Rails 3.2.9. When I add CoffeeScript code to a .js.coffee file in the /app/assets/javascripts directory, I get the resulting JavaScript in all of my webpages. The problem is all the JavaScript is wrapped in:

(function() {
  // my code
}).call(this);

So any methods I define are not visible in any other CoffeeScript code I write in other files. What's the proper way to write a set of reusable CoffeeScript classes and methods with Rails?

I'm using Rails 3.2.9. When I add CoffeeScript code to a .js.coffee file in the /app/assets/javascripts directory, I get the resulting JavaScript in all of my webpages. The problem is all the JavaScript is wrapped in:

(function() {
  // my code
}).call(this);

So any methods I define are not visible in any other CoffeeScript code I write in other files. What's the proper way to write a set of reusable CoffeeScript classes and methods with Rails?

Share Improve this question asked Nov 15, 2012 at 6:43 at.at. 52.6k105 gold badges304 silver badges471 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

The simplest thing to do is to namespace all your classes. If your application is called "app" then in your initialization code before anything else happens:

// Set up the namespace.
window.app = { }

and then in all your .coffee files:

class app.Pancakes
    #...

Then you'd have a global namespace and you'd reference everything through that namespace:

pancakes = new app.Pancakes

Similarly for simple functions:

app.where_is = (pancakes, house) -> ...

# And elsewhere...
x = app.where_is(...)

There are various ways of setting up and partially hiding the namespace but they're all variations on the above and simple namespacing plays nicely with the Rails asset pipeline.

Also, you can define classes within the coffeescript files like this:

class this.Person
  constructor: (attr = {}) ->
    ...

In that way, the definitions are attached to the global namespace.

发布评论

评论列表(0)

  1. 暂无评论