microevent.coffee 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # This is a simple port of microevent.js to Coffeescript. I've changed the
  2. # function names to be consistent with node.js EventEmitter.
  3. #
  4. # microevent.js is copyright Jerome Etienne, and licensed under the MIT license:
  5. # https://github.com/jeromeetienne/microevent.js
  6. nextTick = if WEB? then (fn) -> setTimeout fn, 0 else process['nextTick']
  7. class MicroEvent
  8. on: (event, fct) ->
  9. @_events ||= {}
  10. @_events[event] ||= []
  11. @_events[event].push(fct)
  12. this
  13. removeListener: (event, fct) ->
  14. @_events ||= {}
  15. listeners = (@_events[event] ||= [])
  16. # Sadly, there's no IE8- support for indexOf.
  17. i = 0
  18. while i < listeners.length
  19. listeners[i] = undefined if listeners[i] == fct
  20. i++
  21. nextTick => @_events[event] = (x for x in @_events[event] when x)
  22. this
  23. emit: (event, args...) ->
  24. return this unless @_events?[event]
  25. fn.apply this, args for fn in @_events[event] when fn
  26. this
  27. # mixin will delegate all MicroEvent.js function in the destination object
  28. MicroEvent.mixin = (obj) ->
  29. proto = obj.prototype || obj
  30. # Damn closure compiler :/
  31. proto.on = MicroEvent.prototype.on
  32. proto.removeListener = MicroEvent.prototype.removeListener
  33. proto.emit = MicroEvent.prototype.emit
  34. obj
  35. module.exports = MicroEvent unless WEB?