JSFiddle - React, Tailwind, and code Playground
HTML
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/bootstrap/2.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/bootstrap/2.3.1/css/bootstrap-responsive.min.css">
<div class="container">
<div class="page-header">
<h1>RxJS for DOM Bindings AutoComplete example</h1>
<p class="lead">Example to show combining input events such as keyup with Ajax requests</p>
</div>
<div class="row-fluid">
<form role="form">
<div class="form-group">
<label for="textInput">Enter Query for Wikipedia</label>
<input type="text" id="textInput" class="form-control" placeholder="Enter Query...">
</div>
</form>
</div>
<div class="row-fluid">
<ul id="results" class="list-monsters"></ul>
</div>
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/2.1.11/rx.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/2.1.11/rx.binding.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs/2.1.11/rx.time.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/rxjs-dom/2.0.3/rx.dom.js"></script>
CSS
.list-monsters {background:red; position:absolute}
JavaScript
(function (global, undefined) {
// Search Wikipedia for a given term
function searchWikipedia(term) {
var cleanTerm = global.encodeURIComponent(term);
var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=' + cleanTerm + '&callback=JSONPCallback';
return Rx.DOM.Request.jsonpRequestCold(url);
}
function clearChildren(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function main() {
var input = document.querySelector('#textInput'),
results = document.querySelector('#results');
// Get all distinct throttled key up events from the input
var keyup = Rx.DOM.fromEvent(input, 'keyup')
.map(function (e) {
return e.target.value; // Project the text from the input
})
.filter(function (text) {
return text.length > 2; // Only if the text is longer than 2 characters
})
.throttle(750 /* Pause for 750ms */ )
.distinctUntilChanged(); // Only if the value has changed
// Search wikipedia
var searcher = keyup
.map(function (text) { return searchWikipedia(text); })
.switchLatest(); // Ensure no out of order results
var subscription = searcher.subscribe(
function (data) {
// Append the results
clearChildren(results);
var res = data[1];
var i, len, li;
for (i = 0, len = res.length; i < len; i++) {
li = document.createElement('li');
li.innerHTML = res[i];
results.appendChild(li);
}
},
function (error) {
// Handle any errors
clearChildren(results);
var li = document.createElement('li');
...