Skip to content

Instantly share code, notes, and snippets.

@mckennatim
Created August 3, 2016 14:22
Show Gist options
  • Save mckennatim/4165110b33c4bcf78e56788c744a02a0 to your computer and use it in GitHub Desktop.
Save mckennatim/4165110b33c4bcf78e56788c744a02a0 to your computer and use it in GitHub Desktop.
RxJS and Mithril Autocomplete Example
<div id="autocomplete"></div>

RxJS and Mithril Autocomplete Example

An implementation of a Github autocomplete for repo names using RxJS and Mithril

A Pen by Timothy McKenna on CodePen.

License.

var pluck = Rx.helpers.pluck;
var searchGithub = function(term) {
return m.request({
method: "GET",
url: `https://api.github.com/search/repositories?q=${term}`
});
};
var el = document.querySelector("#autocomplete");
var AutoComplete = {
controller() {
this.data = m.prop({});
Rx.Observable.fromEvent(el, "keyup")
.map(pluck("target")) /* get element */
.filter(el => el.matches("input")) /* make sure it is the input */
.map(pluck("value")) /* get element's value */
.filter(val => val.length > 2) /* at least 3 chars */
.debounce(250) /* debounce it */
.distinctUntilChanged() /* ignore non character keyups */
.flatMapLatest(searchGithub) /* fire request */
.subscribe(this.data); /* set data prop with results */
},
view(ctrl) {
var data = ctrl.data();
return m(".autocomplete", [
m("label[for=search]", ["Search for Github repo: "]),
m("input#search[list=results]"),
m("datalist#results", [
data.items && data.items.map(item => m("option[value=" + item.name + "]"))
])
]);
}
};
m.mount(el, AutoComplete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.2/rx.all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.0/mithril.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment