Using Namespaces in CoffeeScript

We previously posted about namespace in CoffeeScript. Using namespace is a useful way of organizing your CoffeeScript into meaningful modules. Unfortunately, it can bloat your code when you are using many classes from the same namespace. I’ve recently started using another helper similar to namespace called using. It takes a list of namespaces and merges them into a temporary context that contains all the properties from each namespace that you’re using:



window.using = (namespaces..., block) ->
  context = {}
  for ns in namespaces
    for k, v of ns
      if context[k]?
        throw "Unable to import namespace: symbol [#{k}] already imported!"
      context[k] = v
  block(context)

Here’s an example of some code that uses a lot of namespaces:



doSomething = =>
  book = new MyApp.Models.Book
  author = new MyApp.Models.Author
  thing = new MyApp.Widgets.Thinger MyApp.Util.escape(book.get('name')), MyApp.Util.escape(author.get('name'))

The use of using cleans up the code and gets the namespace information out the way:



doSomethingToo = =>
  using MyApp.Models, MyApp.Util, MyApp.Widgets, (ctx) =>
    book = new ctx.Book
    author = new ctx.Author
    thing = new ctx.Thinger ctx.escape(book.get('name')), ctx.escape(author.get('name'))