【问题标题】:RxJS wait for 2 separate clicks eventsRxJS 等待 2 个单独的点击事件
【发布时间】:2019-08-15 01:09:00
【问题描述】:

我有一个按钮和一个图像。

当我单击按钮时,我希望它进入某种“等待模式”。 等待两次单独的单击,它们都返回鼠标单击事件的 x、y 值。

我得到了鼠标 xy 部分没问题,但不知道接下来要使用什么 RxJS 运算符

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

【问题讨论】:

    标签: javascript rxjs mouseevent dom-events


    【解决方案1】:

    您可以使用bufferCount 一次发出固定数量的点击(在一个数组中)。

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

    【讨论】:

    • 这真是太好了!我不知道 bufferCount。
    【解决方案2】:

    您可以使用scan 将事件收集为一个数组,然后使用filter 验证数组的长度是否为2:

    const xy = root.pipe(
      map(evt => xyCartoPos(elem, evt)),
      scan((acc, evt) => {
        acc.push(evt);
        return acc;
      }, []),
      filter(events => events.length == 2),
    );
    

    这将导致只有一个包含两个鼠标事件的数组,在两次点击后,被发布给订阅者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多