From 8617cfdd0b319c7c210bd81e4838636d0ffdb023 Mon Sep 17 00:00:00 2001 From: Mike Hatfield Date: Sun, 29 Apr 2012 17:05:07 -0300 Subject: [PATCH] Added recipe for reusing CoffeeScript code in a web application as well as Node.js --- .../syntax/code_reuse_on_client_and_server.md | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 chapters/syntax/code_reuse_on_client_and_server.md diff --git a/chapters/syntax/code_reuse_on_client_and_server.md b/chapters/syntax/code_reuse_on_client_and_server.md new file mode 100644 index 0000000..f7a1aca --- /dev/null +++ b/chapters/syntax/code_reuse_on_client_and_server.md @@ -0,0 +1,90 @@ +--- +layout: recipe +title: Code Reuse on Client and Server +chapter: Syntax +--- +## Problem + +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. + +## Solution + +Export the functionality in the following manner: + +{% highlight coffeescript %} + +# simpleMath.coffee + +# these methods are private +add = (a, b) -> + a + b + +subtract = (a, b) -> + a - b + +square = (x) -> + x * x + +# create a namespace to export our public methods +SimpleMath = exports? and exports or @SimpleMath = {} + +# items attached to our namespace are available in Node.js as well as client browsers +class SimpleMath.Calculator + add: add + subtract: subtract + square: square + +{% endhighlight %} + +## Discussion + +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. + +In Node.js, we can include our module using the `require` command. + +{% highlight console %} + +$ node + +> var SimpleMath = require('./simpleMath'); +undefined +> var Calc = new SimpleMath.Calculator(); +undefined +> console.log("5 + 6 = ", Calc.add(5, 6)); +5 + 6 = 11 +undefined +> + +{% endhighlight %} + +In our web page, we can include our module using by including it as a script. + +{% highlight html %} + + + + + + SimpleMath Module Example + + + + + +

A SimpleMath Example

+ + + + +{% endhighlight %} + +Result: + +#A SimpleMath Example +* 5 + 6 = 11 \ No newline at end of file