Skip to content

Instantly share code, notes, and snippets.

@davidcornu
Created January 19, 2012 17:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidcornu/1641217 to your computer and use it in GitHub Desktop.
Save davidcornu/1641217 to your computer and use it in GitHub Desktop.
Allows CoffeeScript classes to trigger their own events and allow binding to them.
class EventedClass
bind: (event, callback) ->
@eventHandlers ||= {}
@eventHandlers[event] = [] unless @eventHandlers[event]?
@eventHandlers[event].push(callback)
return true
unbind: (event, callback) ->
@eventHandlers ||= {}
if @eventHandlers[event]? && @eventHandlers[event].indexOf(callback) >= 0
@eventHandlers[event].splice(@eventHandlers[event].indexOf(callback), 1)
return true
else
return false
unbindAll: ->
@eventHandlers = {}
return true
trigger: (event, data={}) ->
@eventHandlers ||= {}
if @eventHandlers[event]? && @eventHandlers[event].length > 0
for callback in @eventHandlers[event]
callback(data) if typeof(callback) == 'function'
return true
else
return false
window.EventedClass = EventedClass
@scratchoo
Copy link

Thank you man for sharing this, helped me a lot :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment