我正处于尝试写一些明智的JavaScript的早期阶段。我想基本上以我的应用程序名称命名所有内容,以尽可能避免全球范围,但仍然给我一种访问该地点声明的功能的方法。但是,我不想在功能定义中成为超级词。

我理想的咖啡网就是这样:

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()'

链轮似乎无法做到这一点。

是否有明智的方法可以在我的容器文件中正确的位置需要我的CoffeeScript文件?还是另一种方法来编写模块化代码,该代码使用Coffeescript,链轮和Rails 3.1分为单独的文件?

有帮助吗?

解决方案

我有一个在代码中使用的模块解决方案。

我定义下面的模块

@module "foo", ->
    @module "bar", ->
        class @Amazing
            toString: "ain't it"

令人惊奇的是

foo.bar.Amazing

@module助手的实现是

window.module = (name, fn)->
  if not @[name]?
    this[name] = {}
  if not @[name].module?
    @[name].module = window.module
  fn.apply(this[name], [])

它写在这里的Coffeescript网站上。

https://github.com/jashkenas/coffee-script/wiki/asy-modules-with-coffeescript

其他提示

只需保持模块1.js as-is并使应用程序。JS看起来像这样:

//= require 'module1'

class @MyApp
  ...

  @Module1 = Module1

这会起作用,因为你已经做了 Module1 全球(宣布 class @Module1 等同于写作 @Module1 = class Module1, , 和 @ 指着 window 在这种情况下)和 class @MyApp 身体, @ 指向班级本身。

如果你想 Module1只要 成为全球的财产 MyApp 上课后,您可以添加行

delete window.Module1

这是我用于管理带有链轮的咖啡本的模块化图案(也可以与Rails 4一起使用):

  # utils.js.coffee

  class Utils
    constructor: ->

    foo: ->
      alert('bar!!!')

    # private methods should be prefixed with an underscore
    _privateFoo: ->
      alert('private methods should not be exposed')

  instance = new Utils()

  # only expose the methods you need to.
  # because this is outside of the class,
  # you can use coffee's sugar to define on window

  @utils = foo: instance.foo

  # otherscript.js.coffee 

  //= require utils
  class OtherScript
    constructor: ->
      @utils.foo()         # alerts bar!!!
      @utils._privateFoo() # undefined method error

这种方法的一个缺点是您将对象公开在窗口上。根据您的需求,添加模块加载程序或采用模块周围的一些新ES语法可能是一个不错的选择。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top