Search code examples
javascriptrxjsmouseeventdom-events

RxJS wait for 2 separate clicks events


I have a button and an image.

When I click the button, I want it to go to a "wait mode" of sorts. Waiting for two separate clicks, that both return the x, y value of the mouse click events.

I got the mouse xy part no problem but at loss for what RxJS operator to use next

const elem = document.getElementById("MyImage");
const root = fromEvent(elem, "click");
const xy = root.pipe(map(evt => xyCartoPos(elem, evt)));
xy.subscribe(coords => console.log("xy:", coords));

function xyCartoPos(elem, e) {
  const elemRect = elem.getBoundingClientRect();
  return {
    x: e.clientX - elemRect.x - elemRect.width / 2,
    y: flipNum(e.clientY - elemRect.y - elemRect.height / 2)
  };
}

Solution

  • You can use bufferCount to emit a fixed number of clicks at once (in one array).

    const xy = root.pipe(
      map(evt => xyCartoPos(elem, evt)),
      bufferCount(2),
      //take(1) // use take(1) if you only want to emit one pair of clicks and then complete
    );