Skip to content

Commit 8617cfd

Browse files
committed
Added recipe for reusing CoffeeScript code in a web application as well
as Node.js
1 parent 5f29cec commit 8617cfd

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
---
2+
layout: recipe
3+
title: Code Reuse on Client and Server
4+
chapter: Syntax
5+
---
6+
## Problem
7+
8+
You have created some functionality in CoffeeScript that you wish to use on the client with a web browser and on the server with Node.js.
9+
10+
## Solution
11+
12+
Export the functionality in the following manner:
13+
14+
{% highlight coffeescript %}
15+
16+
# simpleMath.coffee
17+
18+
# these methods are private
19+
add = (a, b) ->
20+
a + b
21+
22+
subtract = (a, b) ->
23+
a - b
24+
25+
square = (x) ->
26+
x * x
27+
28+
# create a namespace to export our public methods
29+
SimpleMath = exports? and exports or @SimpleMath = {}
30+
31+
# items attached to our namespace are available in Node.js as well as client browsers
32+
class SimpleMath.Calculator
33+
add: add
34+
subtract: subtract
35+
square: square
36+
37+
{% endhighlight %}
38+
39+
## Discussion
40+
41+
In the above example, we create a new namespace called SimpleMath. If `export` is available, our class is exported as a Node.js module. If `export` is *not* available, then SimpleMath is added to the global namespace and available to our web page.
42+
43+
In Node.js, we can include our module using the `require` command.
44+
45+
{% highlight console %}
46+
47+
$ node
48+
49+
> var SimpleMath = require('./simpleMath');
50+
undefined
51+
> var Calc = new SimpleMath.Calculator();
52+
undefined
53+
> console.log("5 + 6 = ", Calc.add(5, 6));
54+
5 + 6 = 11
55+
undefined
56+
>
57+
58+
{% endhighlight %}
59+
60+
In our web page, we can include our module using by including it as a script.
61+
62+
{% highlight html %}
63+
64+
<!DOCTYPE HTML>
65+
<html lang="en-US">
66+
<head>
67+
<meta charset="UTF-8">
68+
<title>SimpleMath Module Example</title>
69+
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
70+
<script src="simpleMath.js"></script>
71+
<script>
72+
jQuery(document).ready(function (){
73+
var Calculator = new SimpleMath.Calculator();
74+
var result = $('<li>').html("5 + 6 = " + Calculator.add(5, 6));
75+
$('#SampleResults').append(result);
76+
});
77+
</script>
78+
</head>
79+
<body>
80+
<h1>A SimpleMath Example</h1>
81+
<ul id="SampleResults"></ul>
82+
</body>
83+
</html>
84+
85+
{% endhighlight %}
86+
87+
Result:
88+
89+
#A SimpleMath Example
90+
* 5 + 6 = 11

0 commit comments

Comments
 (0)