3

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())  
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98

1 Answers1

1

You can start the buffering from cancel:

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

See jsFiddle

OlliM
  • 7,023
  • 1
  • 36
  • 47