Last active
December 20, 2015 22:48
-
-
Save eagsalazar/6207239 to your computer and use it in GitHub Desktop.
Add events to regular js objects using coffeescript. .on, .off, and event chaining with bailout when callback returns false.
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
class app.Eventable | |
callbackRegistry = {} | |
@off: (event, callback) -> | |
callbacks = callbackRegistry[event] | |
callbackRegistry[event] = _.without(callbacks, callback) | |
@on: (event, callback) -> | |
if typeof callback == "function" | |
callbackRegistry[event] ||= [] | |
callbackRegistry[event].push callback | |
else | |
throw new Error "callbacks must be functions" | |
@trigger: (event, payload) => | |
console.log "event: #{event}! with : #{payload}" | |
@_runCallbacks event | |
@_runCallbacks: (event) => | |
callbacks = callbackRegistry[event] || [] | |
for callback in callbacks | |
if callback() == false | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment