bacon.js:holdWhen和onValue的奇怪行为

时间:2015-07-03 10:55:47

标签: javascript reactive-programming bacon.js

在这里查看正在运行的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?

1 个答案:

答案 0 :(得分:0)

此行为已被确认为已在0.7.67中修复的错误。

有关详细信息,请参阅here