5

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!!!

Community
  • 1
  • 1
cpow
  • 205
  • 1
  • 4
  • 7

1 Answers1

8

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.

Community
  • 1
  • 1
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Awesome, that is what I was looking for. thanks! I am still new to JS so that helped a lot! – cpow May 08 '12 at 20:58