forked from lookback/meteor-eventbus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventbus.coffee
51 lines (38 loc) · 1014 Bytes
/
eventbus.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
EventBus = ->
listeners = {}
dispatch = (event, data...)->
check event, String
actions = listeners[event]
if actions? and actions.length > 0
actions.forEach (fn) ->
fn.apply(null, data)
addListener = (event, fn) ->
check event, String
check fn, Function
actions = listeners[event] || []
actions.push(fn)
listeners[event] = actions
removeListener = (event, listener) ->
check event, String
check listener, Match.Optional(Function)
if listeners[event]?
if listener
actions = listeners[event]
if actions? and actions.length > 0
index = actions.indexOf(listener)
if index > -1
actions.splice(index, 1)
else
delete listeners[event]
# Public API
# Aliases ...
dispatch: dispatch
add: dispatch
send: dispatch
emit: dispatch
trigger: dispatch
register: addListener
on: addListener
off: removeListener
deregister: removeListener
remove: removeListener