提供一个小工具 events.lua --- NodeJS 的 events 模块的 lua 实现

NodeJS 的 events 模块做的非常人性化,很好用。

我们的客户端项目是 MVC 结构,需要一个灵活的事件传递机制,所以我把 NodeJS 的 events 模块移植到 lua 上。实测下来,很好用

github 地址:https://github.com/yi/events.lua

README:

events.lua

An event emitter implementation in lua, api similar to (http://nodejs.org/api/events.html)

如何使用 Usage



events = require "events"


person =
  name: "Johnny"
  age: "very old"


events.EventEmitter(person)   -- make person an EventEmitter


handlers =
  hello: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


  helloOnce: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


  helloToRemove: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


  goodday: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


person\on "hello", handlers.hello
person\on "hello", handlers.helloToRemove
person\once "hello", handlers.helloOnce
person\on "goodday", handlers.goodday


person\emit "hello", person, 1      -- will fire: hello, helloToRemove, helloOnce
person\emit "hello", person, 2      -- will fire: hello, helloToRemove


person\off "hello", handlers.helloToRemove
person\emit "hello", person, 3      -- will fire: hello


person\emit "goodday", person, 1    -- fire goodday
person\removeAllListeners "hello"


person\emit "hello", person, 4      -- fire no-one
person\emit "goodday", person, 2    -- fire goodday


events.EventEmitter person, true    --should output:  table: 0x7fc142d70500 is already an EventEmitter




支持回调方法的弱引用,简化析构 Weak Reference Support



person =
  name: "Walker"
  age: "long enough"


events.EventEmitter(person, true)   -- (WEAK KEY) make person an EventEmitter


handlers =
  hello: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


  helloOnce: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


  helloToRemove: (who, howmany)->
    print " who:#{who.name}, #{howmany} times"
    assert.are.equal who, person


person\on "hello", handlers.hello
person\on "hello", handlers.helloToRemove
person\once "hello", handlers.helloOnce
person\on "goodday", handlers.goodday


person\emit "hello", person, 1      -- will fire: hello, helloToRemove, helloOnce


handlers.hello = nil
collectgarbage "collect"            -- handlers.hello should be gced
person\emit "hello", person, 2      -- only fire: helloToRemove


Test

Test specs are written in (http://www.moonscript.com/) on (https://github.com/Olivine-Labs/busted)

To run tests, do:

busted -v spec/

赞,好用~~~~~