[Reactive Programming] Using an event stream of double clicks -- buffer()

See a practical example of reactive programming in JavaScript and the DOM. Learn how to detect double clicks with a few operators in RxJS.

<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.22/rx.all.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div class="header">
         <a href="#" class="button">BUTTON</a><h4>-</h4>
    </div>
</body>
</html>
var button = document.querySelector('.button');
var h4 = document.querySelector('h4');

var clicks = Rx.Observable.fromEvent(button, 'click');
var doubleClicks = clicks
    .buffer(() => clicks.throttle(250)) // buffer the events, for each event debounce 250ms and group together
    .map(arr => arr.length) // for each group, count the lengh of event
    .filter(x => x ===2); // only pick length === 2 which means double click


var res = doubleClicks.subscribe( () => {
    h4.textContent = "double click"
});

doubleClicks.throttle(1000).subscribe(() => {
    h4.textContent = "-";
});
原文地址:https://www.cnblogs.com/Answer1215/p/4851858.html