Skip to content

Instantly share code, notes, and snippets.

@benjie
Created April 9, 2012 13:37
Embed
What would you like to do?
CoffeeScript EventListener class
# To use this, just do `EventListener.infect(YourClassHere)`
class EventListener
@infect: (Class) ->
Class::unlistenAll = EventListener::unlistenAll
Class::listenTo = EventListener::listenTo
Class::listenOnceTo = EventListener::listenOnceTo
Class::unlistenTo = EventListener::unlistenTo
unlistenAll: (destroy = true)->
if destroy
@_bg_listeners_destroy = true
if @_bg_listeners?.length > 0
for i in [@_bg_listeners.length-1..0]
[o, e, c] = @_bg_listeners[i]
@unlistenTo o, e, c
delete @_bg_listeners
return
listenTo:(object,event,callback) ->
if @_bg_listeners_destroy
console.log "Attempting to listen for '#{event}' on a destroyed object"
return
@_bg_listeners = [] unless @_bg_listeners
fn = null
if _.isFunction(object.on)
fn = object.on
else if _.isFunction(object.bind)
fn = object.bind
else if _.isFunction(object.addEventListener)
fn = object.addEventListener
else
console.error "No event listener found"
console.dir object
debugger
return
@_bg_listeners.push [object,event,callback]
fn.call object, event, callback
return
listenOnceTo:(object,event,callback) ->
cb = =>
callback.apply @, arguments
@unlistenTo object,event,cb
@listenTo object, event, cb
return
unlistenTo: (object, event, callback) ->
return unless @_bg_listeners
for [o, e, c], i in @_bg_listeners
if o is object and e is event and c is callback
fn = null
if _.isFunction(object.off)
fn = object.off
else if _.isFunction(object.unbind)
fn = object.unbind
else if _.isFunction(object.removeEventListener)
fn = object.removeEventListener
else
console.error "No event unlistener found"
console.dir object
debugger
return
@_bg_listeners.splice(i,1)
fn.call object, event, callback
return
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment