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