Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript command mode


May 09, 2021 CoffeeScript


Table of contents


Command mode

Problem

You need to have another object handle your own executable code.

Solution

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

Discuss

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"