May 09, 2021 CoffeeScript
You need to have another object handle your own executable code.
Use Command pattern to pass a reference to a function.
# Using a private variable to simulate external scripts or modules
incrementers = (() ->
privateVar = 0
singleIncrementer = () ->
privateVar += 1
doubleIncrementer = () ->
privateVar += 2
commands =
single: singleIncrementer
double: doubleIncrementer
value: -> privateVar
)()
class RunsAll
constructor: (@commands...) ->
run: -> command() for command in @commands
runner = new RunsAll(incrementers.single, incrementers.double, incrementers.single, incrementers.double)
runner.run()
incrementers.value() # => 6
With the function as a first-level object and inherited from the variable range of the Javascript function, CoffeeScript makes the language pattern almost visible. In fact, any function that passes a callback function can act as a command.
The jqXHR object returns the jQuery AJAX method using 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"