Skip to content

Instantly share code, notes, and snippets.

@anderssvendal
Created July 5, 2012 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anderssvendal/3055732 to your computer and use it in GitHub Desktop.
Save anderssvendal/3055732 to your computer and use it in GitHub Desktop.
Easy namespacing of classes and objects.
# Easy namespacing of classes and objects.
#
# name - The String containing namespaces up to but not including the class
# name.
#
# Examples
# # Using a class
# class module("Foo.Bar").Baz
# doStuff: ->
# console.log "doing stuff"
#
# baz = new window.Foo.Bar.Baz()
# baz.doStuff()
#
# # Using an object
# module("Foo.Bar").Baz =
# doStuff: ->
# console.log "doing stuff"
#
# window.Foo.Bar.Baz.doStuff()
window.module = (name) ->
segments = name.split(/\./)
# Make sure all the needed objects are created before assigning the class
root = window
for segment in segments
root[segment] ?= {}
root = root[segment]
root
@kimjoar
Copy link

kimjoar commented Jul 5, 2012

Line 27 can be simplified to

root[segment] ?= {}

@anderssvendal
Copy link
Author

Coolio. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment