Skip to content

Instantly share code, notes, and snippets.

@sguzman
Created July 7, 2017 03:50
Show Gist options
  • Save sguzman/4f8e1649a53cff09cbcb331ab4954136 to your computer and use it in GitHub Desktop.
Save sguzman/4f8e1649a53cff09cbcb331ab4954136 to your computer and use it in GitHub Desktop.
Using RxJS to implement a simple counter
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="author" content="Salvador Guzman" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>RxJS Counter</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.min.js"></script>
<script>
Rx.Observable.fromEvent(document, 'click')
.filter(s => s.target.id === 'button1' || s.target.id === 'button2')
.map(s => s.target.id === 'button1'? 1: -1)
.scan((s,t) => s + t, 0)
.subscribe(s => document.getElementById('counter').innerText = s)
</script>
</head>
<body>
<h1>RxJS Counter</h1>
<h2 id="counter">0</h2>
<button id="button1" type="button">Button 1</button>
<button id="button2" type="button">Button 2</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment