-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.js
More file actions
69 lines (52 loc) · 1.25 KB
/
stream.js
File metadata and controls
69 lines (52 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
module.exports = Stream;
function Stream(value, type) {
var _this = this;
var valueType = '';
_this.value = null
_this.listeners = [];
_this.closeListeners = [];
_this.get = function() {
if (valueType === 'getter') {
return _this.value();
}
return _this.value;
};
_this.put = function(value, type) {
if (type === 'getter' && typeof value === 'function') {
valueType = type;
} else if (valueType === 'getter') {
valueType = '';
}
_this.value = value;
};
_this.listen = function(listener) {
_this.listeners.push(listener);
};
_this.notify = function() {
_this.listeners.forEach(call);
};
_this.close = function() {
['get', 'put', 'listener', 'notify', 'close', 'onClose']
.forEach(function(fn) {
_this[fn] = function() {
throw new Error('Stream is closed');
};
});
var closeListeners = this.closeListeners;
this.listeners = null;
this.closeListeners = null;
closeListeners.forEach(call);
};
_this.onClose = function(fn) {
this.closeListeners.push(fn);
};
_this.put(value, type);
}
Stream.getter = function(fn) {
var stream = new Stream();
stream.put(fn, 'getter');
return stream;
};
function call(fn) {
fn();
}