Created
October 7, 2014 12:29
-
-
Save loosechainsaw/9644696ac4608abc39bf to your computer and use it in GitHub Desktop.
rxjsautocomplete.js
This file contains hidden or 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
| window.application = {}; | |
| window.application.search = (function(){ | |
| function searchwikipedia(term) { | |
| return $.ajaxAsObservable({ | |
| url: 'http://en.wikipedia.org/w/api.php', | |
| data: { action: 'opensearch', | |
| search: term, | |
| format: 'json' }, | |
| dataType: 'jsonp' | |
| }); | |
| } | |
| var searchbox = $('#search'); | |
| var selector = $('#results'); | |
| var keypresses = searchbox.keyupAsObservable() | |
| .map( function(ev){ | |
| return $(ev.target).val(); | |
| }); | |
| keypresses.filter( | |
| function(v){ | |
| return v.length < 2; | |
| }) | |
| .forEach( | |
| function() { | |
| selector.text(''); | |
| }, | |
| function(){ | |
| selector.text(''); | |
| }, | |
| function(){ | |
| selector.text(''); | |
| } | |
| ); | |
| var searchableKeypresses = keypresses.filter( | |
| function(v){ | |
| return v.length > 1; | |
| }) | |
| .throttle(100) | |
| .distinctUntilChanged(); | |
| var requests = searchableKeypresses.flatMapLatest(function(term){ | |
| return searchwikipedia(term); | |
| }); | |
| var subscriber = requests.forEach( | |
| function(data){ | |
| selector.text(''); | |
| var elements = data.data['1']; | |
| $.each(elements, function (_, text) { | |
| $('<li>' + text + '</li>').appendTo(selector); | |
| }); | |
| }, | |
| function(error){ | |
| selector.text(''); | |
| $('<li>Error: ' + error + '</li>').appendTo('#results'); | |
| }, | |
| function(){ | |
| } | |
| ); | |
| }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment