3

Consider this example from http://baconjs.github.io/

var up   = $('#up').asEventStream('click');
var down = $('#down').asEventStream('click');

var counter =
  // map up to 1, down to -1
  up.map(1).merge(down.map(-1))
  // accumulate sum
    .scan(0, function(x,y) { return x + y });

// assign observable value to jQuery property text
counter.assign($('#counter'), 'text');

What if I have one more button for resetting counter and an event stream from this button clicks. How do I switch counter stream based on reset clicks stream to reset counter? I know that I have to use .flatMapLatest method, but referring this example I dont know how to do it.

gyzerok
  • 1,338
  • 2
  • 11
  • 26

2 Answers2

3

You don't need flatMapLatest here. You can use a powerful and a much simpler Bacon.update as in this example we have a simple state machine.

var up    = $('#up').asEventStream('click');
var down  = $('#down').asEventStream('click');
var reset = $('#reset').asEventStream('click');

var counter = Bacon.update(0,
  [up],    function (prev, unused) { return prev + 1; },
  [down],  function (prev, unused) { return prev - 1; },
  [reset], function (prev, unused) { return 0; }
);
phadej
  • 11,947
  • 41
  • 78
1

Assuming #reset is a button for resetting

var up   = $('#up').asEventStream('click');
var down = $('#down').asEventStream('click');
var reset = $('#reset').asEventStream('click');

var counter = reset.flatMapLatest(function () {
    return up.map(1).merge(down.map(-1))
             .scan(0, function(x,y) { return x + y });
});

counter.assign($('#counter'), 'text');
gyzerok
  • 1,338
  • 2
  • 11
  • 26