问题描述
我认为 RxJS 应该非常适合抑制重复按钮点击 2 秒.然而,我正在努力实现.
I think RxJS should perfectly fit to supress dublicate button clicks for 2 seconds. However, Im struggleing with the implementation.
var $button = $('#myButton').button();
$button
.toObservable("click")
//.Throttle(2000) // Wouldn't fire the first event instantly :-(
.Subscribe(function(){ alert('clicked'); });
为了您的方便,我已经创建了一个 jsFiddle.你需要在这个小提琴中向下滚动,因为我只是在里面粘贴了 Rx,因为我找不到 CDN.
I already created a jsFiddle for your convenience. You need to scroll down in this fiddle, because I just pasted Rx inside as I couldn't find a CDN.
http://jsfiddle.net/cburgdorf/mUMFA/2/
推荐答案
我将 Sergeys 的答案转换为 JavaScript 并认为这应该是最后的方法.
I converted Sergeys answer into JavaScript and think this should be the final way to go.
var $button = $('#myButton').button();
$button
.toObservable("click")
.Take(1)
.Merge(Rx.Observable.Empty().Delay(2000))
.Repeat()
.Subscribe(function(){ console.log('clicked'); }
根据我的理解,这个解决方案实际上更好,因为它不依赖副作用,这使得它在可组合性方面变得更好.
From my understanding this solutions is actually better because it doesn't rely on a sideeffect which makes it even better in terms of composability.
正如 Sergey 指出的那样,您甚至可以像这样实现自己的组合器:
As Sergey pointed out, you could even go further and implement your own combinator like so:
Rx.Observable.prototype.OneInTime = function(delay){
return this
.Take(1)
.Merge(Rx.Observable.Empty().Delay(delay))
.Repeat();
};
所以我们上面的例子可以简化为:
So our example from above could be reduced to:
var $button = $('#myButton').button();
$button
.toObservable("click")
.OneInTime(2000)
.Subscribe(function(){ console.log('clicked'); });
这篇关于如何采取第一次发生,然后抑制事件 2 秒(RxJS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!