Skip to content

Instantly share code, notes, and snippets.

@rahman541
Created August 2, 2018 07:58
Show Gist options
  • Save rahman541/956c8c05edbaa3234635f190bddc64ef to your computer and use it in GitHub Desktop.
Save rahman541/956c8c05edbaa3234635f190bddc64ef to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>Test with RxJS</title>
</head>
<body>
<input type="text" id="txtinput" placeholder="Search in wikipedia">
<button>Click me</button>
<select id="select"></select>
<ul id="list">
<li>Loading..</li>
</ul>
<script type="text/javascript" src="https://unpkg.com/rxjs@6.2.2/bundles/rxjs.umd.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script type="text/javascript">
// Dom Element
var button = document.querySelector('button');
var txtinput = document.querySelector('#txtinput');
var list = $('#list');
var select = document.querySelector('#select');
// Button click event - Traditional way
// button.addEventListener('click', function(e) {
// return axios.get('https://jsonplaceholder.typicode.com/albums')
// });
rxjs.fromEvent(button, 'click')
.pipe(
rxjs.operators.throttleTime(1000),
rxjs.operators.switchMap( function(e) { // can cancel ajax request
return rxjs.ajax.ajax('https://jsonplaceholder.typicode.com/albums');
}),
)
.subscribe( function(data) {
console.log(data.response);
});
// Textbox
rxjs.fromEvent(txtinput, 'keyup')
.pipe(
rxjs.operators.map(
e => e.target.value // Project the text from the input
),
rxjs.operators.filter(txt => txt.length > 2), // search only more than 2 text
rxjs.operators.debounceTime(750 /* Pause for 750ms */),
rxjs.operators.distinctUntilChanged(), // Only if the value has changed
rxjs.operators.switchMap(
txt => rxjs.ajax.ajax('http://en.wikipedia.org/w/api.php?origin=*&action=opensearch&format=json&search='+txt)
)
)
.subscribe(e => {
list.empty()
.append( $.map(e.response[1], data => $('<li>').text(data)) );
}, err => {
list.empty().append($('<li>')).text('Error. ' + err);
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment