服务端和客户端的代码重用(coffeescript)

本文介绍了如何在CoffeeScript上创建函数并将其应用于网页浏览器和Node.js服务端,通过使用命名空间和模块输出来实现跨平台使用。

问题

当你在 CoffeeScript 上创建了一个函数,并希望将它用在有网页浏览器的客户端和有 Node.js 的服务端时。

解决方案

以下列方法输出函数:

# simpleMath.coffee# these methods are privateadd = (a, b) ->
    a + bsubtract = (a, b) ->
    a - bsquare = (x) ->
    x * x# create a namespace to export our public methodsSimpleMath = exports? and exports or @SimpleMath = {}# items attached to our namespace are available in Node.js as well as client browsersclass SimpleMath.Calculator
    add: add    subtract: subtract    square: square

讨论

在上面的例子中,我们创建了一个新的名为 “SimpleMath” 的命名空间。如果 “export” 是有效的,我们的类就会作为一个 Node.js 模块输出。如果 “export” 是无效的,那么 “SimpleMath” 就会被加入全局命名空间,这样就可以被我们的网页使用了。

在 Node.js 中,我们可以使用 “require” 命令包含我们的模块。

$ node

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

在网页中,我们可以通过将模块作为一个脚本嵌入其中。

<!DOCTYPE HTML><html lang="en-US"><head>
    <meta charset="UTF-8">
    <title>SimpleMath Module Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/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>

输出结果:

A SimpleMath Example

· 5 + 6 = 11


转载于:https://my.oschina.net/wenquan0hf/blog/540641

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值