Last active
August 29, 2015 14:12
-
-
Save bjoerge/0c2f628c937e789a5df5 to your computer and use it in GitHub Desktop.
Minimal rxjs autocomplete impl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on https://github.com/Reactive-Extensions/RxJS/tree/master/examples/autocomplete | |
var Rx = require("rx-dom"); | |
var querystring = require("querystring"); | |
var jsonp = require("jsonp"); | |
function searchWikipedia(term) { | |
return new Promise((resolve, reject) => { | |
var params = querystring.stringify({ | |
search: term, | |
action: 'opensearch', | |
format: 'json' | |
}); | |
jsonp(`http://en.wikipedia.org/w/api.php?${params}`, (err, result)=> { | |
err ? reject(err) : resolve(result); | |
}); | |
}); | |
} | |
function setup() { | |
var textInput = document.getElementById('textInput'); | |
var results = document.getElementById('results'); | |
Rx.DOM.keyup(textInput) | |
.map(e => e.target.value) | |
.filter(text => text.length > 2) | |
.throttle(150) | |
.distinctUntilChanged() | |
.flatMapLatest(searchWikipedia) | |
.map(data => data[1]) | |
.subscribe(writeResults, handleError); | |
function writeResults(res) { | |
results.innerHTML = (res.length ? res : ['No hits']).map(value => `<li>${value}</li>`).join(''); | |
} | |
function handleError(error) { | |
results.innerHTML = `<li>${error}</li>`; | |
} | |
} | |
document.addEventListener('DOMContentLoaded', setup); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment