JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.4.1/rx.all.min.js"></script>
<p>
<a class="btn btn-default btn-large" href="javascript:" role="button" id="2">Click me second</a>
<a class="btn btn-primary btn-large" href="javascript:" role="button" id="1">Click me first</a>
<span id="result"></span>
</p>
<p>Buttons clicked: <span id="clicked"></span></p>
JavaScript
/*
RxJS is an implementation of Reactive Extensions, an asynchronous stream
library available for multiple languages. In Rx the intent is to make code
more declarative and stateless by modeling events as streams. The below code
illustrates this using a simple example, but the real power of the library
lies in being able to convert events that are not UI related, such as
promises, into composable streams.
*/
// Dom
var buttonOne = $('#1');
// convert click events to a stream of events
var buttonOneClickStream = Rx.Observable.fromEvent(buttonOne, 'click');
var buttonTwo = $('#2');
var buttonTwoClickStream = Rx.Observable.fromEvent(buttonTwo, 'click');
var result = $('#result');
var clicked = $('#clicked');
// Streams
var clickedAnything = buttonOneClickStream
// convert the click events to the integer value 1
.map(function () { return 1; })
.merge(
// merge this stream with the 2nd button's stream, which
// will output 2s via map
buttonTwoClickStream.map(function() { return 2; })
);
// only emit a value for further consumption after we've buffered
// two values. the emitted value is an array with length = count
var lastTwoClicks = clickedAnything
.bufferWithCount(2);
// helper function to see if we received values 1 then 2 from
// the array we get from bufferWithCount
var firstThenSecond = function (arr) {
return arr[0] === 1 && arr[1] === 2;
};
var clickedFirstThenSecond = lastTwoClicks
// only emit a value if it passes the filter function
.filter(firstThenSecond);
var clickedOtherPattern = lastTwoClicks
.filter(
function (arr) { return !firstThenSecond(arr); }
);
// Results
// subscribe is the final consumer of a stream, but there can
// be multiple subscribers to the same stream. if a stream has
// no subscribers, it never executes (since nobody is listening)
var updateClicks = clickedAnything.subscribe(function(x) {
clicked.text(clicked.text() + " " + x);
});
var clearResultOnClick =...