git ssb

1+

Matt McKegg / mutant



Tree: 91e3d5d798ebcef85048597e9a56b9f579613469

Files: 91e3d5d798ebcef85048597e9a56b9f579613469 / value.js

982 bytesRaw
1module.exports = Observable
2
3function Observable (value, opts) {
4 var listeners = []
5 value = getValue(value, opts)
6
7 observable.set = function (v) {
8 value = getValue(v, opts)
9
10 var cachedListeners = listeners.slice(0)
11 for (var i = 0, len = cachedListeners.length; i < len; i++) {
12 cachedListeners[i](value)
13 }
14 }
15
16 return observable
17
18 function observable (listener) {
19 if (!listener) {
20 return value
21 }
22
23 if (typeof listener !== 'function') {
24 throw new Error('Listeners must be functions.')
25 }
26
27 listeners.push(listener)
28
29 return function remove () {
30 for (var i = 0, len = listeners.length; i < len; i++) {
31 if (listeners[i] === listener) {
32 listeners.splice(i, 1)
33 break
34 }
35 }
36 }
37 }
38}
39
40function getValue (value, opts) {
41 if (value == null) {
42 if (opts && opts.defaultValue != null) {
43 value = opts.defaultValue
44 } else {
45 value = null
46 }
47 }
48 return value
49}
50

Built with git-ssb-web