-
Notifications
You must be signed in to change notification settings - Fork 11
/
watch-all.js
54 lines (45 loc) · 1.04 KB
/
watch-all.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
50
51
52
53
54
var resolve = require('./resolve')
var isObservable = require('./is-observable')
var onceIdle = require('./once-idle')
module.exports = watchAll
function watchAll (observables, listener, opts) {
if (!Array.isArray(observables)) {
observables = [ observables ]
}
var broadcasting = false
var releases = observables.map(bind, broadcast)
broadcast()
return function () {
releases.forEach(tryInvoke)
releases.length = 0
}
function broadcast () {
if (opts && opts.idle) {
if (!broadcasting) {
broadcasting = true
onceIdle(broadcastNow)
}
} else if (opts && opts.nextTick) {
if (!broadcasting) {
broadcasting = true
setImmediate(broadcastNow)
}
} else {
broadcastNow()
}
}
function broadcastNow () {
broadcasting = false
listener.apply(this, observables.map(resolve))
}
}
function bind (value) {
if (isObservable(value)) {
return value(this)
}
}
function tryInvoke (value) {
if (typeof value === 'function') {
return value()
}
}