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

Code reuse for the CoffeeScript service side and clients


May 09, 2021 CoffeeScript


Table of contents


Code reuse on the service side and on the client side

Problem

When you create a function on CoffeeScript and want to use it on clients with web browsers and service .js Node.

Solution

Output functions in the following ways:

# 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

Discuss

In the example above, we created a new namespace called SimpleMath. I f "export" is valid, our class will output as a node .js module. If "export" is invalid, "SimpleMath" is added to the global namespace so that it can be used by our web page.

In the Node .js, we can use the "require" command to include our modules.

$ node

> var SimpleMath = require('./simpleMath');
undefined
> var Calc = new SimpleMath.Calculator();
undefined
> console.log("5 + 6 = ", Calc.add(5, 6));
5 + 6 =  11
undefined
>

In a Web page, we can embed a module as a script.

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>SimpleMath Module Example</title>
    <script src="https://atts.w3cschool.cn/attachments/image/wk/coffeescript/jquery.min.js"></script>
    <script src="simpleMath.js"></script>
    <script>
        jQuery(document).ready(function    (){
            var Calculator = new SimpleMath.Calculator();
            var result = $('<li>').html("5 + 6 = " + Calculator.add(5, 6));
            $('#SampleResults').append(result); 
        });
    </script>
</head>
<body>
    <h1>A SimpleMath Example</h1>
    <ul id="SampleResults"></ul>
</body>
</html>

Output:

A SimpleMath Example

ยท 5 + 6 = 11