问题描述
伙计们,我有一个使用 RxJS 来处理鼠标事件的应用程序.我正在将这些事件组合成更复杂的可观察手势".其中一种手势是摇晃".
Folks, I have an app using RxJS to handle mouse events. I am composing these events into more complex observable 'gestures'. One such gesture is "shake".
我尝试编写的一系列事件是:
The series of events I am trying to compose are:
mousedown
mousemove left
mousemove right
mousemove left
mousemove right
mouseup
我发现的是
mousedown
mouseup
mousemove left
mousemove right
mousemove left
mousemove right
也触发了相同的结果.
我的一般问题是:你如何在 RxJS 中表达一个 observable,比如 mouseup,应该取消并重新启动一个 observable 的组合?
My question in general is: How do you express in RxJS that a obeservable, such as mouseup, should cancel and restart the composition of an observable?
作为问题的另一个例子(来自同一个小提琴),以下事件
As another example of the issue (from the same fiddle), the following events
mousedown
mouseup
mousedown
mouseup
mousedown
mousemove left
mousemove right
mousemove left
mousemove right
导致 3 个震动事件.我希望结果是一个.
Result in 3 shake events. I would like it to result in one.
推荐答案
使用 takeUntil
var down = $div.onAsObservable('mousedown');
var up = $div.onAsObservable('mouseup');
var move = $div.onAsObservable('mousemove');
var shake = down.flatMapLatest(function (downev) {
var current = downev;
return move
.map(function (ev) {
var delta = ev.pageX - current.pageX;
current = ev;
return delta < 0 ? 'left' : 'right';
})
.takeUntil(up)
.toArray();
})
.subscribe(function (moves) {
// see if moves is an array of left,right,...
这篇关于如何取消组合的 RxJS observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!