Skip to content

Instantly share code, notes, and snippets.

@demux
Created August 27, 2015 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demux/2cbf9cead5be39b2d657 to your computer and use it in GitHub Desktop.
Save demux/2cbf9cead5be39b2d657 to your computer and use it in GitHub Desktop.
class SimpleEventEmitter:
_events: []
_onceWrapper: (type) ->
wrapper = ~>
@off(type, wrapper)
fn.apply(this, arguments)
on: (type, fn, once=false) !->
@_events[type] = @_events[type]? or []
if once
@_events[type].push(@_onceWrapper(type)(fn))
else
@_events[type].push(fn)
once: (type, fn) !->
@on(type, fn, true)
off: (type, fn) !->
for event, i in @_events[type]? or []
if event.toString! in [fn.toString!, @_onceWrapper(type)(fn)]
@_events.splice(i, 1)
emit: (type) !->
args = Array.prototype.slice.call(arguments)
args.shift!
for event in @_events[type]? or []
event.apply(this, args)
EventEmitter.addListener = EventEmitter.on
EventEmitter.removeListener = EventEmitter.off
EventEmitter.trigger = EventEmitter.emit
module.exports = SimpleEventEmitter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment