Skip to content

Commit 65b8a95

Browse files
committed
Merge branch 'new_recipes'
2 parents e2ee5b2 + 2c9f909 commit 65b8a95

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
---
2+
layout: recipe
3+
title: Command Pattern
4+
chapter: Design Patterns
5+
---
6+
## Problem
7+
8+
You need to let another object handle when your private code is executed.
9+
10+
## Solution
11+
12+
Use the [Command pattern](http://en.wikipedia.org/wiki/Command_pattern) to pass along references to your functions.
13+
14+
{% highlight coffeescript %}
15+
# Using a private variable to simulate external scripts or modules
16+
incrementers = (() ->
17+
privateVar = 0
18+
19+
singleIncrementer = () ->
20+
privateVar += 1
21+
22+
doubleIncrementer = () ->
23+
privateVar += 2
24+
25+
commands =
26+
single: singleIncrementer
27+
double: doubleIncrementer
28+
value: -> privateVar
29+
)()
30+
31+
class RunsAll
32+
constructor: (@commands...) ->
33+
run: -> command() for command in @commands
34+
35+
runner = new RunsAll(incrementers.single, incrementers.double, incrementers.single, incrementers.double)
36+
runner.run()
37+
incrementers.value() # => 6
38+
{% endhighlight %}
39+
40+
## Discussion
41+
42+
With functions as first-class objects and with the function-bound variable scope inherited from Javascript, the CoffeeScript language makes the pattern nearly invisible. In fact, any function passed along as callbacks can act as a *Command*.
43+
44+
The `jqXHR` object returned by jQuery AJAX methods uses this pattern.
45+
46+
{% highlight coffeescript %}
47+
jqxhr = $.ajax
48+
url: "/"
49+
50+
logMessages = ""
51+
52+
jqxhr.success -> logMessages += "Success!\n"
53+
jqxhr.error -> logMessages += "Error!\n"
54+
jqxhr.complete -> logMessages += "Completed!\n"
55+
56+
# On a valid AJAX request:
57+
# logMessages == "Success!\nCompleted!\n"
58+
{% endhighlight %}
59+

wanted-recipes.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ foo 1, 2, 3
109109

110110
* Behavioral Patterns
111111
* Chain of Responsibility
112-
* Command
113112
* Iterator
114113
* Mediator
115114
* Observer

0 commit comments

Comments
 (0)