Skip to content

Instantly share code, notes, and snippets.

@Bondifrench
Last active March 7, 2016 09:05
Show Gist options
  • Save Bondifrench/481a0f3903b606e13580 to your computer and use it in GitHub Desktop.
Save Bondifrench/481a0f3903b606e13580 to your computer and use it in GitHub Desktop.
A mithril autocomplete component using Horsey by @JAForbes
var pluck = require("lodash").pluck;
var groupBy = require("lodash").groupBy;
var forceRender = require("lodash").identity;
var m = require("mithril");
var horsey = require("horsey");
var controller = function controller(label, data, property) {
//split the data set into subsets for performance
this.grouped = groupBy(data, function (suggestion) {
return suggestion[property][0];
});
this.label = label;
this.data = data;
this.property = property;
this.getter = function (suggestion) {
return suggestion[property];
};
};
var horseyConfig = function horseyConfig(ctrl) {
return function (el, isInit, context) {
var current_char = el.value.charAt(0).toUpperCase();
var suggestions = ctrl.grouped[current_char] || [];
var different_sublist = current_char != context.previous_char;
if (!context.horsey) {
context.horsey = horsey(el, {
suggestions: suggestions,
getValue: ctrl.getter,
getText: ctrl.getter,
limit: 10
});
}
if (different_sublist) {
context.horsey.clear();
suggestions.forEach(function (s) {
return context.horsey.add(s);
});
}
context.onunload = function () {
return context.horsey.destroy();
};
context.previous_char = current_char;
};
};
var view = function view(ctrl) {
return m("div", m("label", ctrl.label, m("input", {
config: horseyConfig(ctrl),
oninput: forceRender
})));
};
module.exports = { view: view, controller: controller };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment