relu-core
Version:
122 lines (97 loc) • 2.19 kB
JavaScript
var rp = require("../");
var base = require("../lib/base");
function stream() {
// fake stream
var a = {
send: function(msg) {
process.nextTick(function() {
console.log("stream a -> b: ", msg);
b.onmessage(JSON.stringify(msg));
});
},
onmessage: function() {}
};
var b = {
send: function(msg) {
process.nextTick(function() {
console.log("stream b -> a: ", msg);
a.onmessage(JSON.stringify(msg));
});
},
onmessage: function() {}
};
return [a, b];
}
function withPauses() {
var x = [].slice.call(arguments);
var y = x.shift();
if(!y) return;
y();
process.nextTick(function() {
withPauses.apply(null, x);
});
}
function synchronizedRp(stream) {
var p = rp.variable();
var remoteChange = false;
p.onUpdated(function(v) {
if(remoteChange) return;
stream.send(["updated", v]);
});
p.onAdded(function(i, v) {
if(remoteChange) return;
stream.send(["added", i, v]);
});
p.onRemoved(function(i) {
if(remoteChange) return;
stream.send(["removed", i]);
});
p.onNested(function(e, p, a, b) {
if(remoteChange) return;
stream.send([p, e, a, b]);
});
stream.onmessage = function(msg) {
msg = JSON.parse(msg);
remoteChange = true;
var changedProperty = p;
if(Array.isArray(msg[0])) {
changedProperty = p.g.apply(p, msg[0]);
msg = msg.slice(1);
}
switch(msg[0]) {
case "updated":
changedProperty.set(msg[1]);
break;
case "added":
changedProperty.splice(msg[1], 0, msg[2]);
break;
case "removed":
changedProperty.splice(msg[1], 1);
break;
}
remoteChange = false;
};
return p;
}
var streams = stream();
var a = synchronizedRp(streams[0]).scope();
var b = synchronizedRp(streams[1]).scope();
withPauses(function() {
a.set(123);
}, function() {
console.log(b());
// logs: 123
a.set([1, 2, {a: 3}]);
}, function() {
console.log(b());
// logs: [1, 2, {a: 3}]
console.log(b.shift());
// logs: 1
}, function() {
console.log(a());
// logs: [2, {a: 3}]
a(1, "a").set(4);
}, function() {
console.log(b());
// logs: [2, {a: 4}]
});