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