Skip to content

Instantly share code, notes, and snippets.

@alumican
Created October 4, 2012 09:25
Show Gist options
  • Save alumican/3832496 to your computer and use it in GitHub Desktop.
Save alumican/3832496 to your computer and use it in GitHub Desktop.
AS3 like EventDispatcher
class EventDispatcher
constructor: () ->
@_listeners = {}
addEventListener: (type, listener) ->
return unless typeof listener == 'function'
@_listeners[type] ?= []
for l in @_listeners[type]
return if l == listener
@_listeners[type].push(listener)
removeEventListener: (type, listener) ->
return unless hasEventListener(type)
for l, i in @_listeners[type]
@_listeners[type].splice(i, 1) if l == listener
delete @_listeners[type] if @_listeners[type].length == 0
removeAllEventListeners: (type = '') ->
if type == '' then @_listeners = {} else delete @_listeners[type]
hasEventListener: (type) ->
return @_listeners[type]?
dispatchEvent: (type, args = null) ->
return unless hasEventListener(type)
for l in @_listeners[type]
l.apply(this, args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment