设置的CoffeeScript / JavaScript类和可用的方法来Rails应用程序的其余部分

2019-07-03 20:30发布

我使用Rails 3.2.9。 当我添加的CoffeeScript代码到一个.js.coffee在文件/app/assets/javascripts目录,我得到了我所有的网页所产生的JavaScript。 问题是所有的JavaScript被包裹在:

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

所以我定义任何方法都没有在任何其他的CoffeeScript代码,我在其他文件写入可见。 什么是写一组可重用CoffeeScript的类和方法使用Rails的正确方法?

Answer 1:

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.



Answer 2:

此外,您还可以像这样的CoffeeScript文件中定义类:

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

通过这种方式,定义被附加到全局命名空间。



文章来源: Set of CoffeeScript/JavaScript classes and methods available to rest of Rails app