如何获得RxJ中按钮状态的可观察值?

时间:2018-12-15 15:39:49

标签: rxjs

我有以下观察值:

mouseOver$      // fired when mouse enters button
mouseOut$       // fired when mouse leaves button
mouseDown$      // fired when mouse button is pressed (over button)
globalMouseUp$  // fired when mouse button is released (anywhere)

我想实现的目标如下:

mouseOver: state changes to 'hover'
mouseOut: state changes to 'normal'
mouseDown: state changes to 'active'
gloalMouseUp: state changes to 'normal'

收获:

如果状态为active(鼠标按钮按下)并且鼠标离开按钮,则状态应更改为normal。当鼠标再次进入按钮而没有释放鼠标按钮时,状态应为active。如果在按钮外释放鼠标按钮,则状态应为hover

我只是不依靠单独的状态变量来保持“活动”状态就无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

已经知道了

let active$ = merge(
  mouseDown$.pipe(map(() => true)),
  globalMouseUp$.pipe(map(() => false))
).pipe(startWith(false));

let hover$ = merge(
  mouseOver$.pipe(map(() => true)),
  mouseOut$.pipe(map(() => false))
);

let state$ = combineLatest(active$, hover$).pipe(
  map(([active, hover]) => hover ? (active ? 'active' : 'hover') : 'normal')
)