Choices
by whelkaholism
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/choices.js/public/assets/styles/choices.min.css">
<script src="https://cdn.jsdelivr.net/npm/choices.js/public/assets/scripts/choices.min.js"></script>
<div>
<select data-bind="choices: { boundField: Choice, items: Choices, src: find, multiple: IsMultiple }">
</select>
</div>
JavaScript
(function()
{
var _getConfig = function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
{
var cfg = ko.unwrap(f_valueaccessor());
var res = {
obs: cfg.boundField,
src: cfg.src,
multiple: ko.unwrap(cfg.multiple) || false,
options: cfg.options || {},
_current: cfg.items || ko.observableArray()
};
return res;
};
ko.bindingHandlers.choices = {
init:
function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
{
var cfg = _getConfig(el, f_valueaccessor, allbindings, viewmodel, bindingcontext);
cfg.multiple && el.setAttribute('multiple');
var chc = new Choices(el, {
searchChoices: false,
shouldSort: false,
shouldSortItems: false
});
chc.setChoices(function()
{
return cfg.src(chc, { initial: true, term: null });
});
el.addEventListener('search', function(e)
{
console.log('search', e);
chc.setChoices(function() { return cfg.src(chc, { initial: false, term: e.detail.value }) });
});
},
update:
function(el, f_valueaccessor, allbindings, viewmodel, bindingcontext)
{
}
};
})();
var model = new function()
{
this.Choice = ko.observableArray();
this.IsMultiple = ko.observable(false);
this.find = function(sender, eargs)
{
return new Promise(function(resolve)
{
setTimeout(function()
{
resolve([{ value: 1, label: 'Hello' }, { value: 2, label: 'World' }]);
}, 100);
});
};
};
ko.applyBindings(model);