在这里查看正在运行的CodePen:http://codepen.io/djskinner/pen/JdpwyY
// Animation start events push here
var startBus = new Bacon.Bus();
// Animation end events push here
var endBus = new Bacon.Bus();
// Balance updates push here
var balanceBus = new Bacon.Bus();
// A Property that determines if animating or not
var isAnimating = Bacon.update(false,
[startBus], function() { return true; },
[endBus], function() { return false; }
);
// Only update the displayBalance when not animating
var displayBalance = Bacon.update(0,
[balanceBus.holdWhen(isAnimating)], function(previous, x) {
return x;
}
);
setTimeout(function() {
var streamTemplate = Bacon.combineTemplate({
balance: displayBalance
});
// Uncommenting this block changes the way the system behaves
// streamTemplate.onValue(function(initialState) {
// console.log(initialState);
//})();
// Print the displayBalance
streamTemplate.onValue(function(v) {
console.log(v.balance);
});
});
按下余额按钮会生成一个新的随机数。创建的属性使用holdWhen
来限制平衡更新,直到isAnimating
属性变为false。
如果我有兴趣获得streamTemplate
的初始状态,我可能会获得该值并立即取消订阅:
streamTemplate.onValue(function(initialState) {
console.log(initialState);
})();
但是,一旦我执行此操作,displayBalance
属性的行为会有所不同,我不再接收更新。
为什么这种看似惰性的变化会对系统造成如此大的不同?当然,系统的行为不应该取决于某人是否在过去的某个时刻订阅和取消订阅了streamTemplate?