Skip to content

Instantly share code, notes, and snippets.

@frontsideair
Last active March 30, 2017 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frontsideair/fa33345c8416ecd9a6c7e77c7f86151d to your computer and use it in GitHub Desktop.
Save frontsideair/fa33345c8416ecd9a6c7e77c7f86151d to your computer and use it in GitHub Desktop.
esnextbin sketch

Enter the username of a Github user to get their full name. Request on keystroke with XHR cancellation instead of debounce, which results in less latency and better user experience. Very simple implementation with RxJS. The magic is the .switch operator.

See live on esnextbin, don't forget to open Network tab in DevTools to see cancellation.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ESNextbin Sketch</title>
</head>
<body>
<div id="content">
<input type="text" id="input" />
<span id="output"></span>
</div>
</body>
</html>
import Rx from 'rxjs/Rx'
const input = document.getElementById('input')
const output = document.getElementById('output')
Rx.Observable.fromEvent(input, 'input')
.map(e => e.target.value)
.switchMap(value => {
if (value === '') {
return Rx.Observable.of('')
} else {
return Rx.Observable.ajax(`https://api.github.com/users/${value}`)
.map(xhr => xhr.response.name)
.catch(e => Rx.Observable.of('No such user!'))
}
})
//.switch()
.subscribe(name => { output.innerHTML = name })
{
"name": "esnextbin-sketch",
"version": "0.0.0",
"dependencies": {
"rxjs": "5.1.0"
}
}
'use strict';
var _Rx = require('rxjs/Rx');
var _Rx2 = _interopRequireDefault(_Rx);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var input = document.getElementById('input');
var output = document.getElementById('output');
_Rx2.default.Observable.fromEvent(input, 'input').map(function (e) {
return e.target.value;
}).switchMap(function (value) {
if (value === '') {
return _Rx2.default.Observable.of('');
} else {
return _Rx2.default.Observable.ajax('https://api.github.com/users/' + value).map(function (xhr) {
return xhr.response.name;
}).catch(function (e) {
return _Rx2.default.Observable.of('No such user!');
});
}
})
//.switch()
.subscribe(function (name) {
output.innerHTML = name;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment