Last active
August 30, 2015 20:59
-
-
Save HendrikRoth/2d4fdcd178cb0bc66a24 to your computer and use it in GitHub Desktop.
mithril-autocomplete (horsey)
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
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(label, data, property){ | |
//split the data set into subsets for performance | |
this.grouped = groupBy( data, (suggestion) => suggestion[property][0]) | |
this.label = label | |
this.data = data | |
this.property = property | |
this.getter = ( suggestion ) => suggestion[property] | |
} | |
var horseyConfig = (ctrl) => (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( | |
( s ) => context.horsey.add( s ) | |
) | |
} | |
context.onunload = () => context.horsey.destroy() | |
context.previous_char = current_char | |
} | |
var view = (ctrl) => | |
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