RxJS Autocomplete example

by Julien Roche

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.3.0/Rx.min.js"></script>
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
 <div class="container">
    <div class="page-header">
      <h1>RxJS 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"></ul>
    </div>
  </div>

JavaScript

function searchWikipedia (term) {
    return $.ajax({
        url: 'https://en.wikipedia.org/w/api.php',
        dataType: 'jsonp',
        data: {
            action: 'opensearch',
            format: 'json',
            search: term
        }
    }).promise();
}

const $input = document.querySelector('#textInput');
const $results = $('#results');

// Get all distinct key up events from the input and only fire if long enough and distinct
Rx.Observable.fromEvent($input, 'keyup')

// Project the text from the input
.map(e => e.target.value)

// Only if the text is longer than 2 characters
.filter(text => text.length > 2)

// Pause for 750ms
.debounceTime(750)

// Only if the value has changed
.distinctUntilChanged()

// 입력된 값으로 검색
.switchMap(searchWikipedia)

.subscribe(
    ([,data]) => $results.empty().append(data.map(v => $('<li>').text(v))),
    error => $results.empty().append($('<li>')).text('Error:' + error)
);