-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathsync.js
79 lines (65 loc) · 1.67 KB
/
sync.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
var hyperdom = require('.')
var h = hyperdom.html
module.exports = function () {
var refresh
var throttle
var promise, awaitingPromise, lastTime, lastValue, timeout
var currentValue
var currentFn
function callFn () {
if (promise) {
if (!awaitingPromise) {
promise.then(function () {
promise = undefined
awaitingPromise = undefined
sync()
})
awaitingPromise = true
}
} else {
var result = currentFn(currentValue)
if (result && typeof result.then === 'function') {
promise = result
promise.then(refresh)
}
valueChanged()
lastTime = Date.now()
}
}
function valueHasChanged () {
return lastValue !== normalisedValue(currentValue)
}
function valueChanged () {
lastValue = normalisedValue(currentValue)
}
function sync () {
var now = Date.now()
if (valueHasChanged()) {
if (!lastTime || (lastTime + throttle < now)) {
callFn()
} else if (!timeout) {
var timeoutDuration = lastTime - now + throttle
timeout = setTimeout(function () {
timeout = undefined
callFn()
}, timeoutDuration)
}
}
}
return function (value, options, fn) {
if (typeof options === 'function') {
fn = options
options = undefined
}
refresh = h.refresh
throttle = options && options.hasOwnProperty('throttle') && options.throttle !== undefined ? options.throttle : 0
currentValue = value
currentFn = fn
sync()
}
}
function normalisedValue (value) {
return value.constructor === Object || value instanceof Array
? JSON.stringify(value)
: value
}