Andreas Köberle
Andreas Köberle

Reputation: 110922

How to react on a takeUntil stream in baconJS

I have 3 event streams for mouseDown, mouseUp and mouseMove. This works so far that when a user not hit the alt Key it does something on mouse move until mouse up.

this.mouseDown
   .filter((e) =>!e.altKey)
   .flatMap(() => this.mouseMove.takeUntil(this.mouseUp))
   .onValue((e) => this.setState({previewEndPoint: this.getNearestPoint(e)}));

My question is how can I react on the mouse up event in this case?

Upvotes: 2

Views: 226

Answers (2)

OlliM
OlliM

Reputation: 7113

Setting a variable in doActionand using it elsewhere is really bad sign and unnecessary. I refactored your code to use combined streams instead.

var moveStart = this.mousedown
  .filter((e) =>!e.altKey && !e.metaKey)    

var move = moveStart.flatMap((e) =>
    this.mousemove
        .takeUntil(this.mouseup)
        .startWith(this.getNearestPoint(e))
  );

var startPoint = moveStart.map((e) => this.getNearestPoint(e))

var endPoint = move.map((e) => this.getNearestPoint(e))

var preview = startPoint.combine(endPoint, (start, end) => {
    preview: true,
    startPoint: start,
    previewEndPoint: end
})

preview.onValue((state) => this.setState(state));

move.onEnd(this.endLine.bind(this));

Upvotes: 2

Andreas Köberle
Andreas Köberle

Reputation: 110922

I had to create a stream that ist started by mouse down and is converted into the mouse move event using flatMap which will then stop on mouse up. Then I have just to listen to onValue and onEnd

var move = this.mousedown
  .filter((e) =>!e.altKey && !e.metaKey)
  .doAction((e) => startPoint = this.getNearestPoint(e))
  .flatMap(() => this.mousemove.takeUntil(this.mouseup));

move.onValue((e) => this.setState({
  preview: true,
  startPoint: startPoint,
  previewEndPoint: this.getNearestPoint(e)
}));

move.onEnd(this.endLine.bind);

Upvotes: 1

Related Questions