Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes within Coffeescript 'Namespace'

Tags:

coffeescript

I found this snippet on the Coffeescript FAQ for creating simplistic namespaces ..

# Code:
#
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

# Usage:
#
namespace 'Hello.World', (exports) ->
  # `exports` is where you attach namespace members
  exports.hi = -> console.log 'Hi World!'

namespace 'Say.Hello', (exports, top) ->
  # `top` is a reference to the main namespace
  exports.fn = -> top.Hello.World.hi()

Say.Hello.fn()  # prints 'Hi World!'

That is all well and good, but I am having a great deal of trouble doing this with the class keyword. Such that ..

namespace 'Project.Something', (exports) ->
   exports.something = -> class something
    // .. code here
   exports.somethingElse = class somethingElse extends something

can anyone shed some light on the syntax that would accomplish this?

like image 922
Ciel Avatar asked Jan 04 '12 17:01

Ciel


1 Answers

Even better, the class syntax allows for the name to actually be in the form of a member, so you can actually just do:

namespace 'Secrets', (exports) ->
  class exports.Hello
    constructor: ->
      @message = "Secret Hello!"

a = new Secrets.Hello
console.log a.message

Full fiddle here: http://jsfiddle.net/7Efgd/1/

like image 156
Chris Subagio Avatar answered Oct 31 '22 07:10

Chris Subagio