Skip to content

Instantly share code, notes, and snippets.

@sguzman
Created June 22, 2017 16:21
Show Gist options
  • Save sguzman/b24019cd4374171dd63830d7306b59d6 to your computer and use it in GitHub Desktop.
Save sguzman/b24019cd4374171dd63830d7306b59d6 to your computer and use it in GitHub Desktop.
Simple incrementer/decrementer with rxjs
<!DOCTYPE html>
<html lang="en">
<head>
<title>RxJS Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.1/Rx.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
</head>
<body>
<h1>RxJS Button Increment/Decrement Example :)</h1>
<button id="inc">+</button>
<span>
<p id="view">0</p>
</span>
<button id="dec">-</button>
<script defer>
var counter = 0;
var inc$ = Rx.Observable.fromEvent($('#inc'), 'click').scan(x => counter + 1, 0).do(x => counter = x).subscribe(x => $('#view')[0].innerText = x);
var dec$ = Rx.Observable.fromEvent($('#dec'), 'click').scan(x => counter - 1, 0).do(x => counter = x).subscribe(x => $('#view')[0].innerText = x);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment