Skip to content

Instantly share code, notes, and snippets.

@clohr
Created September 12, 2015 16:42
Show Gist options
  • Save clohr/6930b1c1a7685a8d171d to your computer and use it in GitHub Desktop.
Save clohr/6930b1c1a7685a8d171d to your computer and use it in GitHub Desktop.
RxJS Autocomplete
var $input = document.getElementById('term');
var $results = document.getElementById('results');
var keyups = Rx.Observable
.fromEvent($input, 'keyup')
.map(function(e) {
$results.innerHTML = '';
return e.target.value;
})
.filter(function(text) {
return text.length > 2;
});
var throttled = keyups.throttle(500);
var distinct = throttled.distinctUntilChanged();
var searchWikipedia = function searchWikipedia(term) {
return $.ajax({
url: 'https://en.wikipedia.org/w/api.php',
dataType: 'jsonp',
data: {
action: 'opensearch',
format: 'json',
search: term
}
}).promise();
};
var suggestions = distinct.flatMapLatest(searchWikipedia);
suggestions.subscribe(
function(data) {
var res = data[1];
$.each(res,
function(_, value) {
$('<li>' + value + '</li>').appendTo($results);
});
},
function(error) {
$('<li>Error: ' + error + '</li>').appendTo($results);
}
);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RxJS Autocomplete</title>
</head>
<body>
<input type="text" id="term"/>
<div id="results"></div>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.22/rx.all.js"></script>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment