2013-02-06 43 views
0

相關:Classes within Coffeescript 'Namespace'如何在Node中使用coffeescript的命名空間代碼?

好的,所以在閱讀該文章後,我抓住了命名空間函數並將其放在它自己的文件中。

namespace.coffee

namespace = (target, name, block) -> 
    [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3 
    top = target 
    target = target[item] or= {} for item in name.split '.' 
    block target, top 
    console.log "created namespace "+ name 


root = exports ? window 
root.namespace = namespace 

,然後在REPL:

> namespace = require('./assets/js/namespace.js').namespace 
[Function]            

如果我的toString()它,它的正確。

好了,現在我想用它:ns.coffee(由桑德羅的答案)

namespace = require('./namespace.js').namespace 

class MyFirstClass 
    myFunc:() -> 
    console.log 'works' 

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

namespace "Project.Something", (exports) -> 
    exports.MyFirstClass = MyFirstClass 
    exports.MySecondClass = MySecondClass 
    console.log 'done with exports' 

然後我在REPL運行:

NS =需要(」 ./資產/ JS /ns.js')#編譯ns.coffee
其中出口完成
創建命名空間Project.Something
{}

它似乎並沒有被工作:

> ns.MyFirstClass            
undefined              
> ns.MySecondClass            
undefined              
> ns.Project.Something.MySecondClass       
TypeError: Cannot read property 'Something' of undefined  

上午我做錯了什麼嗎?

回答

0

exports變量是module.exports對於您從引用它的文件。因此,當您撥打namespace時,它會更改exports,這是從require中返回的namespace,而不是從require中返回的那個ns

請注意,namespace需要3個參數,但其中的第一行基本上使得target可選。如果你通過target(你可能想要exports,或者exports ? window,如果這需要在服務器和客戶端運行),那麼它應該做你想做的。

+0

似乎如果是這樣的話,我不會看到來自命名空間文件的控制檯日誌消息,但我這樣做:「創建名稱空間Project.Something」 – jcollum

+0

@jcollum爲什麼不呢? 'namespace'的參數可以很好地傳遞。 –

+0

當然,該代碼正在運行,但它顯然不創建名稱空間,或者我錯誤地調用它。 – jcollum