是否有可能在一个时间范围内使用Rx for JavaScript观察数字特定的dom事件
问题描述:
我试图在一个时间范围内发生特定次数的dom事件(keyup)时收到通知。我看到有一个油门在一段时间内抛出事件,我想要数它们。例如,如果在500毫秒内文本框的密钥事件发生10次,我只想通知它。是否有可能在一个时间范围内使用Rx for JavaScript观察数字特定的dom事件
答
可以通过保存点击的时间戳和10次点击前与当前时间戳比较点击的时间戳实现这一目标:
(我假设你在这里使用jQuery)
var timestamps = [];
$('.watched').click(function() {
var now = (new Date).getTime();
// add the current timestamp in front of the other timestamps
timestamps.unshift(now);
if (timestamps.length > 10 && (now - timestamps[10]) < 500) {
// do whatever you really wanted to do
clickedTenTimes()
}
// clean unneeded timestamps
while (timestamps.length > 10) timestamps.pop()
});
答
您可以使用groupByUntil函数在500毫秒内触发的关键事件创建可观察组。然后只计算每个可观察组中的事件。如果一个组中有十个或更多的事件,那么做一些事情。
var keyups = $('#input').keyupAsObservable()
.groupByUntil(
function(x) { return x.currentTarget.id; },
function(x) { return x; },
function(x) { return Rx.Observable.timer(500); }
);
keyups.subscribe(function(obs) {
obs.count()
.filter(function(count) { return count >= 10; })
.subscribe(doSomething)
});
谢谢,这可以按要求工作。但是,它可以通过事件处理程序轻松完成。如果可能的话,我想用Rx来处理所有的“时间戳”。 –
直到现在我还没有使用Rx,但是我会看看。 – Tharabas