我正处于尝试编写一些明智的 Javascript 的早期阶段。我想基本上以我的应用程序名称命名所有内容,以尽可能避免全局变量,但仍然给我一种访问在该位置周围声明的函数的方法。但是,我不想在函数定义中过于冗长。
我理想的 CoffeeScript 应该是这样的:
class @MyApp
@myClassMethod = ->
console.log 'This is MyApp.myClassMethod()'
class @Module1
@moduleMethod = ->
console.log 'This is MyApp.Module1.moduleMethod()'
你得到图片。这样我就避免了MyApp.Module.submoduleMethod = ->
每次我想正确定义命名空间函数时都必须编写 -在@
我的类定义中使用和定义事物可以使事情变得简洁明了。
这一切都很顺利,直到我想将我的功能拆分为多个 CoffeeScript 文件。那么我真正想要的是这样的:
// application.js
class @MyApp
//= require 'module1'
//= require 'module2'
// module1.js
class @Module1
@moduleMethod = ->
console.log 'This is STILL MyApp.Module1.moduleMethod()'
Sprockets 似乎无法做到这一点。
有没有一种明智的方法来要求我的 CoffeeScript 文件在我的容器文件中的正确位置?或者使用 CoffeeScript、Sprockets 和 Rails 3.1 编写模块化代码的另一种方法?