Files: bd426f70b20582a00fe0bfa9e1fca8d3d28f0acc / lib / lazy-watcher.js
1575 bytesRaw
1 | module.exports = function (update, onBind, onUnbind) { |
2 | var lazy = false |
3 | |
4 | var obj = { |
5 | live: false, |
6 | suspended: false, |
7 | broadcast: broadcast, |
8 | update: update, |
9 | value: null, |
10 | listeners: [], |
11 | |
12 | transaction: function (value, cb) { |
13 | var originalValue = obj.suspended |
14 | obj.suspended = true |
15 | cb(value) |
16 | obj.suspended = originalValue |
17 | obj.broadcast() |
18 | }, |
19 | |
20 | onUpdate: function () { |
21 | if (update()) { |
22 | broadcast() |
23 | } |
24 | }, |
25 | |
26 | checkUpdated: function () { |
27 | if (!obj.live || lazy) { |
28 | lazy = false |
29 | update() |
30 | } |
31 | }, |
32 | |
33 | getValue: function () { |
34 | obj.checkUpdated() |
35 | return obj.value |
36 | }, |
37 | |
38 | addListener: function (listener) { |
39 | if (typeof listener !== 'function') { |
40 | throw new Error('Listeners must be functions.') |
41 | } |
42 | |
43 | obj.listeners.push(listener) |
44 | |
45 | if (!obj.live) { |
46 | obj.live = true |
47 | lazy = true |
48 | onBind() |
49 | } |
50 | |
51 | return function release () { |
52 | for (var i = 0, len = obj.listeners.length; i < len; i++) { |
53 | if (obj.listeners[i] === listener) { |
54 | obj.listeners.splice(i, 1) |
55 | break |
56 | } |
57 | } |
58 | if (!obj.listeners.length && obj.live) { |
59 | obj.live = false |
60 | onUnbind() |
61 | } |
62 | } |
63 | } |
64 | } |
65 | |
66 | return obj |
67 | |
68 | // scoped |
69 | |
70 | function broadcast () { |
71 | if (!obj.suspended) { |
72 | var cachedListeners = obj.listeners.slice(0) |
73 | for (var i = 0, len = cachedListeners.length; i < len; i++) { |
74 | cachedListeners[i](obj.value) |
75 | } |
76 | } |
77 | } |
78 | } |
79 |
Built with git-ssb-web