当 web.js 遇上 Eisa…
发布于 3年前 作者 be5invis 1897 次浏览

鄙人的 Eisa 虽说目前还很原始,但是基本上已经可以用了。基于 Necessaria 包管理器摆平客户端,Node 摆平服务器,你就可以结合 Eisa 语言的优点和无数已有的 JavaScript 类库,轮子不用造了,人参更美满了……



本文直接ネタ小问的文章,源码都是照抄来的,并换成了等价的 Eisa 形式。我省略了包导入的部分。



Backbone?很简单

// Eisa version by Belleve Invis


// Note that chained(f) returns a function.
// syntax:
// def f(x) = expression
// def f(x): statements end
def chained(f) = function:
f.apply this, arguments
return this
end

// Model of Backbone
def Person = Backbone.model.extent {
sayHello: chained { alert "Hey, I'm " + @get('name') + "." },
setName: chained {|name|
@set {'name': name}
alert "My name is " + @get('name') + "."
}
}

var Will = Person.new()
Will |.setName 'Will Wen Gunn'
|.sayHello

Mustache —— 做异步很简单啊!

由于 Eisa 自带异步库和阻塞原语,所以就不用朴灵兄的 EventProxy 啦,直接上!


// 注意:async 库是浏览器专用的

// 源码在 src/lib/async.js

do async.async {
def results = async.join! {
data: {|resend| $.getJSON(location.origin + '/persons', resend) },
template: {|resend| $.get(location.origin + '/tmpls/persons.html', resend) }
};
$('body').append Mustache.to_html(results.template, results.data)
}

相比 EventProxy,这里流程既简单又清楚。

async.async
会处理包含异步调用(这里是
async.join
,看那个感叹号)的代码块(这玩意叫阻塞原语),把它变成使用类似自动机的机构。
async.join
会平行地启动多个任务并且聚合它们,结果会合成为一个对象“返回”。


Web.js 的 router

def urlRouter = {

'^(\d{4})\/(\d{2})\/(\d{2})\/(.*)\.jpg': '$1-$2-$3-$4.jpg',
'google': 'http://www.google.com',
'iwillwen': 'http://www.iwillwen.com'
}
def getRouter = {
'^getsomthing': function(req, res, qs):
res.sendJSON qs
end,
'^car': function(req, res, qs):
case qs.action:
when 'foo': res.send 'Your action is foo'
when 'bar': res.send 'Your action is bar'
end
end
}
def postRouter = {
'^postsomthing': function(req, res, data):
res.sendJSON qs
end,
'^car': function(req, res, data):
case data.action:
when 'foo': res.send 'Your action is foo'
when 'bar': res.send 'Your action is bar'
end
end
}

web.run urlRouter, 80
|.get getRouter
|.post postRouter;

console.log 'The app is running on http://localhost'

从案例可以看出,第一,因为 Eisa 有真正的常量,原先很多用 var 的“常量”如今有了名分;第二,Eisa 的函数可以省略括弧,进一步减少冗余的字符数;第三,Eisa 的多路分支没有贯穿(fall through),语义更加明确。



各位可以去 http://github.com/infinte/eisa 来围观我的项目。

1 回复

我对语言无所谓,不过确实懒得学一门为了语言而语言的语言。

回到顶部