Search code examples
javascriptfrpbacon.js

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?


Solution

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