namespace: a CoffeeScript Nugget

I recently stumbled upon the namespace function in CoffeeScript’s FAQ. It helps me follow the module pattern by writing code like this:


namespace "Matt.Printer", (exports) ->
  message1 = "Yo ho ho"
  message2 = "Five dwarves"

  exports.print1 = ->
    console.log message1

  exports.print2 = ->
    console.log message2

Instead of like this:


window.Matt = {}
Matt.Printer = (->
  message1 = "Yo ho ho"
  message2 = "Five dwarves"

  print1 = ->
    console.log message1

  print2 = ->
    console.log message2

  {
    print1: print1
    print2: print2
  }
)()

On its own it isn’t much, but multiply a few less lines of code and visual noise across a dozen coffee files and you’ve got a nice payoff. I think it also reads quite nicely.

The CoffeeScript FAQ has a few other tidbits as well; I encourage you to take a look at it from time to time.

Conversation
  • Dustin says:

    It should be mentioned that the namespace function is not built into CoffeeScript but the FAQ has a snippet of code to create it.

    https://gist.github.com/934418

  • […] previously posted about namespace in CoffeeScript. Using namespace is a useful way of organizing your CoffeeScript into meaningful modules. […]

  • Comments are closed.