How to switch streams based on some EventStream changes in Bacon

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 another button to reset the counter and a stream of events from that button. How to switch the counter flow based on the click flow reset to the reset counter? I know I need to use the .flatMapLatest method, but referring to this example, I don't know how to do it.

+3


source to share


2 answers


You don't need here flatMapLatest

. You can use the powerful and 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; }
);

      

+3


source


Assuming which #reset

is the button to reset



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');

      

+1


source







All Articles