Tag Archive: JavaScript

CoffeeScript 是在JavaScript 基础上增加了很多易读的语法糖的新一代编程语言。

CoffeeScript 编译成 JavaScript 在客户端执行,或者在 NodeJS 服务器端执行。它的语法本质就是 JavaScript ,但是提高了代码的可读性。

在 JavaScript 基础上增加了很多 Ruby Python 的语法特性。比如,用缩进代替括号,取消了作为行结束的分号,简化function定义, 用 @ 符号替代OO编程中到处用到的 this 。

增加了很多编程的强制规范,比如默认变量为局部变量,函数最后一行为返回值。

提供了很多 JavaScript 编程经常用到的模式,比如可以给函数提供默认值,改进的循环处理。

由于 CoffeeScript 编译为 JavaScript ,所以可以在任何需要 JavaScript 的地方用 CoffeeScript 取代它。如果说 Web 开发的趋势是 HTML5 和 服务器端 JavaScript 。那么 Web 开发的趋势就是 CoffeeScript 。你可以只写一种优雅的现代语言 CoffeeScript 。

CoffeeScript 编写和开发环境

以 Ubuntu 为例

需要安装 NodeJS 作为编译器环境

安装 npm 包管理器

安装 coffee-script 编译器

npm install -g coffee-script

安装 VIM 插件 vim-coffee-script

然后在 VIM 中执行 

:CoffeeCompile watch vert

这样在右边窗口开发 CoffeeScript ,可以在左边窗口实时查看被编译成的 JavaScript
也可以用命令行 coffee -c test.coffee 来手动编译

常用的 CoffeeScript 语法例子

定义一个连续数组

numbers = [0..3]  

循环操作数列

sites = ['blog.eood.cn','www.eood.cn','google.com']
for site in sites
 alert site

甚至可以这样

sites = ['blog.eood.cn','www.eood.cn','google.com']
alert site for site in sites

定义函数

myfunc = (arg) ->
  alert arg

或者

myfunc:  ->
  alert 'ok'

定义复杂对象

kids =
  brother:
    name: "Max"
    age:  11
  sister:
    name: "Ida"
    age:  9

同过 JQuery 操作 DOM

$('.account').attr class: 'active‘

定义类和类的继承

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

绑定事件函数到 DOM 对象

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart

CoffeeScript 实际生产环境的使用

可以结合 JQuery, Backbone JS 或者所有的 JavaScript 开发框架来开发复杂的前端应用和服务器端应用。37signals 利用了 CoffeeScript + BackboneJS 开发了 HTML5 的手机客户端程序。用 CoffeeScript 来书写 JavaScript 可以减少代码量,不降低代码执行效率,降低开发成本。

 

JSONP enable you to send request to other domain beyond the same domain policy. And the corss domain alternative to AJAX.

JSONP is natively supported by JQuery, Zepto (alternative to JQuery for mobile usages). But When you require JSONP and DO NOT want to add the huge JQuery to your code base. This library will be useful.

var JSONP = (function () {
    var counter = 0,
        head, query, key, window = this;

    function load(url) {
        var script = document.createElement('script'),
        var done = false;
        script.src = url;
        script.async = true;

        script.onload = script.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                done = true;
                script.onload = script.onreadystatechange = null;
                if (script && script.parentNode) {
                    script.parentNode.removeChild(script);
                }
            }
        };
        if (!head) {
            head = document.getElementsByTagName('head')[0];
        }
        head.appendChild(script);
    }

    function jsonp(url, params, error, callback) {
        query = "?";
        params = params || {};
        for (key in params) {
            if (params.hasOwnProperty(key)) {
                query += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
            }
        }
        var jsonp = "json" + (++counter);
        window[jsonp] = function (data) {
            callback(data);
            try {
                delete window[jsonp];
            } catch (e) {}
            window[jsonp] = null;
        };

        load(url + query + "callback=" + jsonp);

        error = error ||
        function () {};

        window.setTimeout(function () {
            if (typeof window[jsonp] == "function") {

                // replace success with null callback in case the request is just very latent.
                window[jsonp] = function (data) {
                    try {
                        delete window[jsonp];
                    } catch (e) {}
                    window[jsonp] = null;
                };

                // call the error callback
                error();

                // set a longer timeout to safely clean up the unused callback.
                window.setTimeout(function () {
                    if (typeof window[jsonp] == "function") {
                        try {
                            delete window[jsonp];
                        } catch (e) {}
                        window[jsonp] = null;
                    };
                }, 120000);
            };
        }, 10000);

        return jsonp;
    }
    return {
        get: jsonp
    };
}());

/*
Example:
----------------

var url = 'http://blog.eood.cn/api';
var error = function() {alert('error');};
var success = function(data) {
        // process the data
};
JSONP.get( url, {'parm1': 'parm1_value', 'parm2': 'parm2_value'}, error, success);

*/

The nodejs growing very fast recently. New library or framework added to nodejs  almost everyday, since it is very easy to build a nodejs based module and javascript is used very widely.

I have done the A/B testing of nodeJS vs Erlang mochiweb, Erlang misultin, Nginx static page on my poor VM machine, and got the following result:

Nodejs helloworld:                     724 qps

Erlang mochiweb helloworld:     430 qps

Erlang misultin helloworld:         690 qps

Nginx static page:                    1045 qps

You can see that nodeJS is bloody fast thanks to the good performance of V8 JavaScript engine.

Talk about server side javascript, you should say Rhino, but nodejs is 20x faster than Rhino. NodeJS is stable, and not seen a bug of the code, like Nginx. You can build asynchronous system based on nodeJS and drop Tornado. What is important is that you can reuse your code both on client side and server side.

NodeJS is good at heavy IO usage, but not heavy CPU usage. And you should not change your current web system to nodeJS since it is too young.You can build your JSON interface by NodeJS, construct JSON from data fetched from database or remote web service, output the JSON format result.

Nodejs library:

npm — A node package manager that uses CommonJS-compatible package.json files, written in asynchronous JavaScript.

Express — A robust feature rich web development framework inspired by Sinatra

nodemachine — A port of WebMachine to Node.js

Connect — A  middleware framework for node

Socket.io — WebSocket-compatible server and client with fallback for legacy browsers

node-mysql — A node.js module implementing the MySQL protocol

redis2json — Easily loads data from Redis into structured JS object

See more:

https://github.com/joyent/node/wiki/modules