RxJS through Bacon

by queryj

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/bacon.js/0.6.8/Bacon.js"></script>
<body>
    <div class="container">
        <div class="page-header">
            <h1>Reactive Djuizing <small>in JavaScript</small></h1>
        </div>
        <input id="textInput" type="text" class="form-control"/>
        <ul id="results"></ul>
    </div>
</body>

JavaScript

$(function () {
    var throttledInput = $('#textInput').
        asEventStream("keyup").
        map(function (ev) {
            return $(ev.target).val();
        }).
        filter(function (text) {
            return text.length > 2;
        }).
        throttle(500).
        skipDuplicates();
    
    function searchWikipedia(term) {
        return Bacon.fromPromise($.ajax({
            url: 'http://en.wikipedia.org/w/api.php',
            data: { action: 'opensearch',
                   search: term,
                   format: 'json' },
            dataType: 'jsonp'
        }));
    }
    
    var suggestions = throttledInput.flatMapLatest(function (text) {
        console.debug('Searching wiki', text);
        return searchWikipedia(text);
    });
    
    var selector = $('#results');
    suggestions.onValue(function (data) {
            console.debug('Data!', data);
            selector.empty();
            $.each(data[1], function (_, text) {
                $('<li>' + text + '</li>').appendTo(selector);
            });
        })
    suggestions.onError(function (e) {
            console.debug("ERROR!", e);
            selector.empty();
            $('<li>Error: ' + e + '</li>').appendTo('#results');
        }
    );
});