Skip to content

Instantly share code, notes, and snippets.

@danallison
Last active August 29, 2015 14:05
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 danallison/a4e4baf67d663fa29164 to your computer and use it in GitHub Desktop.
Save danallison/a4e4baf67d663fa29164 to your computer and use it in GitHub Desktop.
Bare bones event system
dispatcher = {}
dispatcher._subscribers = {}
dispatcher.on = (eventName, callback, context) ->
(dispatcher._subscribers[eventName] or = [])
.push {
callback: callback
context: context
}
return ->
dispatcher.off eventName, callback, context
return
dispatcher.off = (eventName, callback, context) ->
subscribers = dispatcher._subscribers[eventName]
if subscribers
i = subscribers.length
while i--
s = subscribers[i]
if s.callback is callback and s.context is context
subscribers.splice i, 1
return
dispatcher.trigger = (eventName, args...) ->
subscribers = dispatcher._subscribers[eventName]
if subscribers
for s in subscribers
s.callback.apply s.context, args
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment