git ssb

1+

Matt McKegg / mutant



Tree: 17c19a6e1cebd8d78dde3d7e061cb8327f773013

Files: 17c19a6e1cebd8d78dde3d7e061cb8327f773013 / lib / lazy-watcher.js

1259 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 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 obj.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 = obj.listeners.length; i < len; i++) {
40 if (obj.listeners[i] === listener) {
41 obj.listeners.splice(i, 1)
42 break
43 }
44 }
45 if (!obj.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 = obj.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