RxJS autocomplete

by jacobwsmith

HTML

<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.lite.js"></script>
<!-- <script src="https://code.jquery.com/jquery.js"></script>
<script src="rx.lite.js"></script> 
-->
<p>Start typing and autocomplete suggestion from Wikipedia will populate below</p>
<p><a href="https://github.com/jacobwsmith/rxjs-autocomplete" target="_blank">Source code</a></p>
<label for="input">Search <input id="input" type="text" value="" />
<div id="results"></div>

JavaScript

// Source code: https://github.com/jacobwsmith/rxjs-autocomplete
// Referencing https://github.com/Reactive-Extensions/RxJS
// Difference between promises and observables: https://egghead.io/lessons/rxjs-rxjs-observables-vs-promises
// Tutuorial of RxJS: http://reactivex.io/learnrx/
$(document).ready(function () {

    // ====================================================
    // We'll get the user input from an input, 
    // listening to the keyup event by using the 
    // Rx.Observable.fromEvent method. This will either 
    // use the event binding from jQuery, Zepto, AngularJS, 
    // Backbone.js and Ember.js if available, and if not, 
    // falls back to the native event binding. This gives 
    // you consistent ways of thinking of events depending 
    // on your framework, so there are no surprises.
    // ====================================================
    var $input = $('#input'), // text input with keyup
        $results = $('#results'); // suggestive results returned 

    // ====================================================
    // Only get the value from each key up
    // ====================================================
    var keyups = Rx.Observable.fromEvent($input, 'keyup')
        .pluck('target', 'value')
        .filter(function (text) {
        return text.length > 2;
    });

    // ====================================================
    // Now debounce the input for 500ms
    // ====================================================
    var debounced = keyups.debounce(500 /* ms */ );

    // ====================================================
    // Now get only distinct values, so we eliminate the 
    // arrows and other control characters
    // ====================================================
    var distinct = debounced.distinctUntilChanged();

    // ====================================================
    // Search Wikipedia 
    // Now, let's query Wikipedia! In RxJS, we can 
    // instantly bind to any...