Skip to content

Instantly share code, notes, and snippets.

@Cfeusier
Last active October 9, 2015 01:28
Show Gist options
  • Save Cfeusier/06125ff8807d3a43f209 to your computer and use it in GitHub Desktop.
Save Cfeusier/06125ff8807d3a43f209 to your computer and use it in GitHub Desktop.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.0/rx.all.min.js"></script>
</head>
<body>
<h1>RxJs Click Counter</h1>
<button id="clicker">Increase Count</button>
<button id="ender">Unsubscribe from Click Stream</button>
<script>
var count = 0,
btnCount = document.getElementById('clicker'),
btnEnd = document.getElementById('ender'),
endO = Rx.Observable.fromEvent(btnEnd, 'click');
function counter() {
console.log(++count);
}
function resultLogger() {
alert(
'Final Count is ' +
count +
'\n Button clicks are not being counted from this point forward.'
);
}
// no need to keep reference to subscription because .dispose will be called
// automatically when the endO .onNext method is called
Rx.Observable
// create Observable from 'click' event on the btnCount element
.fromEvent(btnCount, 'click')
// take data from Observable until endO.onNext is called
.takeUntil(endO)
// subscribe to Observable with two handlers:
// .onNext (increases count) and .onCompleted (logs results)
.subscribe({
onNext: counter,
onCompleted: resultLogger
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment