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'); });
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/
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.
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'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With