Last active
August 29, 2015 14:05
-
-
Save danallison/a4e4baf67d663fa29164 to your computer and use it in GitHub Desktop.
Bare bones event system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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