Classes within Coffeescript 'Namespace'

后端 未结 3 2100
天命终不由人
天命终不由人 2020-12-14 10:33

I found this snippet on the Coffeescript FAQ for creating simplistic namespaces ..

# Code:
#
namespace = (target, name, block) ->
  [target, name, block]          


        
相关标签:
3条回答
  • 2020-12-14 10:58

    Even better, the class syntax allows for the name to actually be in the form of a member, so you can actually just do:

    namespace 'Secrets', (exports) ->
      class exports.Hello
        constructor: ->
          @message = "Secret Hello!"
    
    a = new Secrets.Hello
    console.log a.message
    

    Full fiddle here: http://jsfiddle.net/7Efgd/1/

    0 讨论(0)
  • 2020-12-14 11:16

    The trick is to create the class first

    class MyFirstClass
      myFunc: () ->
        console.log 'works'
    
    class MySecondClass
      constructor: (@options = {}) ->
      myFunc: () ->
        console.log 'works too'
        console.log @options
    

    Then somewhere near the end of the file export all the classes than need to be exposed.

    namespace "Project.Something", (exports) ->
      exports.MyFirstClass = MyFirstClass
      exports.MySecondClass = MySecondClass
    

    Later on you can use the classes as so:

    var firstClass = new Project.Something.MyFirstClass()
    firstClass.myFunc()
    
    var secondClass = new Project.Something.MySecondClass 
      someVar: 'Hello World!'
    
    secondClass.myFunc()
    
    0 讨论(0)
  • 2020-12-14 11:23

    How about using something like this?

    module =
        Hello: class Hello extends Backbone.Model
            constructor: ->
                @message = 'Hello'
    
        Hello2: class Hello2 extends Backbone.View
            constructor: ->
                @message = 'Hello2'
    
    0 讨论(0)
提交回复
热议问题