You need to let another object handle when your private code is executed.
Command pattern to pass along references to your functions.
# Using a private variable to simulate external scripts or modules
incrementers = (() ->
privateVar = 0
singleIncrementer = () ->
privateVar += 1
doubleIncrementer = () ->
privateVar += 2
single : singleIncrementer
double : doubleIncrementer
value : -> privateVar
constructor : ( @ commands ...) ->
run : -> command () for command in @ commands
runner = new RunsAll ( incrementers . single , incrementers . double , incrementers . single , incrementers . double )
runner . run ()
incrementers . value () # => 6 Discussion
jqXHR object returned by jQuery AJAX methods uses this pattern.
jqxhr = $ . ajax
url : "/"
logMessages = ""
jqxhr . success -> logMessages += "Success! \n "
jqxhr . error -> logMessages += "Error! \n "
jqxhr . complete -> logMessages += "Completed! \n "
# On a valid AJAX request:
# logMessages == "Success!\nCompleted!\n"