Skip to content

Instantly share code, notes, and snippets.

@eagsalazar
Last active December 20, 2015 22:48
Show Gist options
  • Save eagsalazar/6207239 to your computer and use it in GitHub Desktop.
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.
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