Hi everyone: I am trying to create a namespace so I can use a class in different coffeescript files throughout my application (at least that is my understanding of what you use a namespace for)
I found a very good example here: Classes within Coffeescript 'Namespace'
excerpt:
namespace "Project.Something", (exports) ->
exports.MyFirstClass = MyFirstClass
exports.MySecondClass = MySecondClass
However, when I implement this, I am getting: namespace is not defined in my console.
My namespace is implemented exactly how it looks in the example above. It seems that my namespace definition is just not being recognized by coffeescript somehow.
any ideas? could there be a versioning issue here or something?
thanks in advance!!!
The namespace
function from that question:
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
isn't part of CoffeeScript, you have to define that helper yourself. Presumably you don't want to repeat it in every file so you'd have a namespace.coffee
file (or util.coffee
or ...) that contains the namespace
definition. But then you're left with the problem of getting your namespace
function into the global namespace. You could do it by hand:
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
(exports ? @).namespace = namespace
# or just (exports ? @).namespace = (target, name, block) -> #...
Demo: http://jsfiddle.net/ambiguous/Uv646/
Or you could get funky and use namespace
to put itself into the global scope:
namespace = (target, name, block) -> #...
namespace '', (exports, root) -> root.namespace = namespace
Demo: http://jsfiddle.net/ambiguous/3dkXa/
Once you've done one of those, your namespace
function should be available everywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With