Yury Tarabanko
Yury Tarabanko

Reputation: 45106

Bacon.js restart buffering when another EventStream fires

I'm trying to make a simple canvas-drawing app using Bacon.js. It should allow to draw a line by selecting start and end point using mouse clicks like this.

points = paper.asEventStream('click')
  .map((e) -> x: e.pageX, y: e.pageY)
  .bufferWithCount(2)

So far so good. Now it should allow to cancel starting point selection by clicking Esc.

cancel = doc.asEventStream('keypress')
  .map((e) -> e.keyCode)
  .filter((key) -> key is 27)
  .map(true)

What is the baconian way of restarting buffering?
UPD: The implementation I've got so far looks awful.

points
  .merge(cancel)
  .buffer(undefined, (buffer) ->
    values = buffer.values
    if values.some((val) -> val is true) then values.length = 0
    else if values.length is 2 then buffer.flush())  

Upvotes: 3

Views: 162

Answers (1)

OlliM
OlliM

Reputation: 7113

You can start the buffering from cancel:

var filteredPairs = cancel.startWith(true).flatMapLatest(function() {
  return points.bufferWithCount(2)
})

See jsFiddle

Upvotes: 1

Related Questions