-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterface-factory.js
110 lines (95 loc) · 2.9 KB
/
interface-factory.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var compute = require('can-compute');
function makeEmitter(emitter) {
return typeof emitter === 'function' ? {
emit: emitter
} : emitter;
}
function callUnsubscribe(unsubscribe, method) {
if (typeof unsubscribe === 'function') {
unsubscribe();
}
if (typeof unsubscribe === 'object' && method && typeof unsubscribe[method] === 'function') {
unsubscribe[method]();
}
}
var config = {
streamConstructor: function(){},
async: true,
emitMethod: 'emit',
on: '',
off: ''
};
module.exports = function(options) {
options = Object.assign({}, config, options);
var streamConstructor = options.streamConstructor,
emitMethod = options.emitMethod,
_async = options.async,
on = options.on,
off = options.off;
return Object.assign({}, {
toStream: function(compute) {
return streamConstructor(function(_emitter) {
var emitter = makeEmitter(_emitter);
var handle = function onComputeChange(ev, value) {
emitter[emitMethod](value)
},
currentValue = compute();
compute.on('change', handle);
if (currentValue !== undefined) {
emitter[emitMethod](currentValue);
}
return function () {
compute.off('change', handle);
};
});
},
toCompute: function(makeStream, context) {
var emitter,
lastValue,
streamHandler,
lastSetValue,
emitter,
unsubscribe,
setterStream = streamConstructor(function(_emitter) {
emitter = makeEmitter(_emitter);
if( lastSetValue !== undefined) {
emitter[emitMethod](lastSetValue);
}
}),
valueStream = makeStream.call(context, setterStream);
// Create a compute that will bind to the resolved stream when bound
return compute(undefined, {
// When the compute is read, use that last value
get: function () {
return lastValue;
},
set: function (val) {
if (emitter) {
emitter[emitMethod](val);
} else {
lastSetValue = val;
}
return val;
},
// When the compute is bound, bind to the resolved stream
on: function (updated) {
// When the stream passes a new values, save a reference to it and call
// the compute's internal `updated` method (which ultimately calls `get`)
streamHandler = function (val) {
lastValue = val;
updated();
};
unsubscribe = valueStream[on](streamHandler);
},
// When the compute is unbound, unbind from the resolved stream
off: function () {
if (unsubscribe) {
callUnsubscribe(unsubscribe, off);
} else if(off) {
valueStream[off](streamHandler);
}
}
});
}
});
};