Skip to content

Instantly share code, notes, and snippets.

@LevelbossMike
Created December 3, 2012 08:25
Show Gist options
  • Save LevelbossMike/4193634 to your computer and use it in GitHub Desktop.
Save LevelbossMike/4193634 to your computer and use it in GitHub Desktop.
Revealing module pattern in coffeescript
@rt = @rt ? {} # create a rt namespace if not already available
@rt.module = ->
name = 'fubar'
hiddenVar = 'this is hidden'
name: (value) ->
return name unless arguments.length
name = value
this
viewHidden: ->
"hiddenVar is: '#{hiddenVar}'"
# test it out
module = @rt.module()
# module-pattern allows us to make variable and methods private
module.name # => returns name function not the variable name
module.name() # => 'fubar'
module.name('something new')
module.name() # => 'something new'
# we can write accessor methods to access the variables we want to make public.
module.hiddenVar # => undefined
module.viewHidden() # => "hiddenVar is: 'this is hidden'"
# it is possible to chain methods when we return the module function in the
# getter/setter methods.
module.name('fubar again').name() # => 'fubar again'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment