-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtraced-dispatch.js
49 lines (41 loc) · 1.31 KB
/
traced-dispatch.js
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
define(function (require) {
var _ = require('underscore')
, dispatch = require('d3-dispatch').dispatch
return function createDispatcher(/* types */) {
var dispatcher = dispatch.apply(
null
, [ 'firstsubscribed', 'lastunsubscribed' ].concat(_.toArray(arguments))
)
, baseOn = dispatcher.on
, listenersMap = {}
dispatcher.hasListeners = hasListeners
dispatcher.on = on
return dispatcher
function hasListeners(type) {
return (type || '').indexOf('.') >= 0
? !!listenersMap[type]
: Object.keys(listenersMap).some(matchesType)
function matchesType(key) {
return key == type || (key.indexOf(type + '.') == 0)
}
}
function on(type, listener) {
var baseType = type.split('.', 1)[0]
, hadBaseListeners = hasListeners(baseType)
if (arguments.length > 1) {
if (_.isNull(listener)) {
delete listenersMap[type]
if (hadBaseListeners && !hasListeners(baseType)) {
dispatcher.lastunsubscribed(baseType)
}
} else {
listenersMap[type] = true
if (!hadBaseListeners && hasListeners(baseType)) {
dispatcher.firstsubscribed(baseType)
}
}
}
return baseOn.apply(dispatcher, arguments)
}
}
})