Observables form Events
Learning Observables
by Suman Kumar
HTML
<div class="container">
<button id="btnOne">
Click
</button>
<br><br>
<input type="text" id="textBoxOne">
<input type="text" id="textBoxTwo">
<br><br>
<div id="outputOne"></div>
<br><br>
<div id="outputTwo"></div>
<br><br>
<div id="mouseMoveOutput"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.2/Rx.min.js"></script>
JavaScript
const btnOne = $('#btnOne');
const textBoxOne = $('#textBoxOne');
const textBoxTwo = $('#textBoxTwo');
const outputOne = $('#outputOne');
const outputTwo = $('#outputTwo');
const mouseMoveOutput = $('#mouseMoveOutput');
const btnOne$ = Rx.Observable.fromEvent(btnOne, 'click');
btnOne$.subscribe(
(e) => console.log('Value : ', e),
(err) => console.log(err),
() => console.log('Completed')
);
const textBoxOne$ = Rx.Observable.fromEvent(textBoxOne, 'input');
// We are using Object literal to create Observer.
// Syntax : observable.subscribe({next: NextCallBackFunction, error: ErrorCallBackFunction, complete: CompleteCallBackFunction});
textBoxOne$.subscribe({
next: e => {
if(e.target.value) outputOne.html('Textbox One : ' + e.target.value);
else outputOne.html('');
}
});
const textBoxTwo$ = Rx.Observable.fromEvent(textBoxTwo, 'input');
// We are directly passing functions to create Observer.
// This is a short hand notation, which will internally create Observer using
// -- Observer One --
textBoxTwo$.subscribe(
(e) => {
if(e.target.value) outputTwo.html('Textbox Two : ' + e.target.value);
else outputTwo.html('');
}
);
// -- Observer Two, to demonstrate that a single Observable can have multiple Observables --
textBoxTwo$.subscribe(
(e) => {
console.log('Observer Two : ', e.target.value);
}
);
const mouseMoveOutput$ = Rx.Observable.fromEvent(document, 'mousemove');
mouseMoveOutput$.subscribe(
(e) => {
mouseMoveOutput.html('X: '+ e.clientX + ' & Y: ' + e.clientY);
}
);