Created
February 10, 2013 03:30
-
-
Save kn0ll/4748254 to your computer and use it in GitHub Desktop.
event listener and event emitter classes inspired by backbone.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# event emitter is an object which is | |
# responsible for triggering events, and binding | |
# functions to those events. | |
class EventEmitter | |
# events map event names | |
# to functions which are bound | |
# to that event. calling model.on evt, fn | |
# will add that function to the events hash. | |
events: null | |
# puts the function inside. | |
# @events[evt] = [fn, fn] | |
on: (evt, fn) -> | |
evts = @events ?= [] | |
e = evts[evt] ?= [] | |
e.push fn | |
# removes the listener references on this emitter. | |
# if `fn` is passed in, it will only remove a specific function. | |
# if `evt`, it will remove all functions for that event. | |
off: (evt, fn) -> | |
evts = @events ?= [] | |
e = evts[evt] ?= [] | |
if fn | |
fn_idx = e.indexOf(fn) | |
e.splice(fn_idx, 1) if fn_idx > -1 | |
else | |
evts[evt] = [] | |
# calls all functions inside. | |
# @events[evt] | |
trigger: (evt) -> | |
fns = @events[evt] or [] | |
for fn in fns | |
fn.apply @, arguments | |
# event listener is an object which manages | |
# event listener references, so they can later | |
# be deallocated. | |
class EventListener | |
# listeners maps models and events to | |
# functions. this is used by listenTo | |
# to keep references of listeners on an emitter. | |
listeners: null | |
# puts the function inside | |
# @listeners[emitter][evt] = [fn, fn] | |
# this allows us to modify events at | |
# the emitter, event, or function level. | |
listenTo: (emitter, evt, fn) -> | |
l = @listeners ?= {} | |
m = l[emitter] ?= {} | |
e = m[evt] ?= [] | |
e.push fn | |
emitter.on evt, fn | |
# removes the listener references on this emitter. | |
# if `fn` is passed in, it will only remove a specific function. | |
# if `evt`, it will remove all functions for that event. | |
# if `emitter`, it will remove all events for that emitter. | |
# of no arguments, all events will be removed. | |
stopListening: (emitter, evt, fn) -> | |
l = @listeners ?= {} | |
m = l[emitter] ?= {} | |
e = m[evt] ?= [] | |
if fn | |
fn_idx = e.indexOf(fn) | |
emitter.off evt, fn | |
e.splice(fn_idx, 1) if fn_idx > -1 | |
else if evt | |
for fn in e | |
emitter.off evt, fn | |
m[evt] = {} | |
else if emitter | |
for evt, fns of m | |
for fn in fns | |
emitter.off evt, fn | |
l[emitter] = {} | |
else | |
for emitter, evts of l | |
for evt, fns of evts | |
for fn in fns | |
emitter.off evt, fn | |
@listeners = {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment