Skip to content

Instantly share code, notes, and snippets.

@clooth
Created September 6, 2012 16:34
Show Gist options
  • Save clooth/3658242 to your computer and use it in GitHub Desktop.
Save clooth/3658242 to your computer and use it in GitHub Desktop.
EventEmitter = () ->
EventEmitter.prototype =
# Add a new listener for an event
bind: (event, func) ->
this._events = this._events or {}
this._events[event] = this._events[event] or []
this._events[event].push(func)
# Remove a listener for an event
unbind: (event, func) ->
this._events = this._events or {}
return false if event in this._eventListeners is false
this._events[event].splice(this._events[event].indexOf(func), 1)
# Emit a specific event and trigger all of its listeners
emit: (event) ->
this._events = this._events or {}
return null if event in this._events is false
for func in this._events[event]
func.apply(this, Array.prototype.slice.call(arguments, 1))
# A mixin function to implement event emitter functionality
# for any class/object
EventEmitter.mixin = (destination) ->
props = ['bind', 'unbind', 'trigger']
for prop in props
destination.prototype[prop] = EventEmitter.prototype[prop]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment