Skip to content

Instantly share code, notes, and snippets.

@philipmat
Created October 8, 2011 05:28
Show Gist options
  • Save philipmat/1271909 to your computer and use it in GitHub Desktop.
Save philipmat/1271909 to your computer and use it in GitHub Desktop.
AsyncEventEmitter
class AsyncEventEmitter
constructor : () ->
@_dict = {}
emit : (eventName, args...) ->
if @_dict[eventName]?
(process.nextTick () ->
callback.apply null, args) for callback in @_dict[eventName]
once : (eventName, callback) ->
if not @_dict[eventName]?
@_dict[eventName] = []
@_dict[eventName].push callback
exports.AsyncEventEmitter = AsyncEventEmitter
#!/usr/bin/env coffee
EventEmitter = require('events').EventEmitter
AsyncEventEmitter = require('./asynceventemitter').AsyncEventEmitter
#emitter = new EventEmitter()
emitter = new AsyncEventEmitter()
foo = (a) ->
a += 1
console.log '0.calc.a'
emitter.emit 'calc.a', a
console.log '1.calc.a'
bar = (b) ->
b += 10
console.log '0.calc.b'
emitter.emit 'calc.b', b
console.log '1.calc.b'
emitter.once 'calc.a', bar
emitter.once 'calc.b', (b) ->
x = (num for num in [1..10000000])
console.log "b=%d", b
foo 1
# 0.calc.a
# 1.calc.a
# 0.calc.b
# 1.calc.b
# b=12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment