git ssb

1+

Matt McKegg / mutant



Tree: 6a2488358b3153546476aba65e4cc9dd5bb5663f

Files: 6a2488358b3153546476aba65e4cc9dd5bb5663f / lib / lazy-watcher.js

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

Built with git-ssb-web