I want to use select2 in knockout.js
for this i have a bindinghandler.
ko.bindingHandlers.select2 = {
init: function(element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
lookupKey = allBindings.lookupKey;
$(element).select2(obj);
if (lookupKey) {
var value = ko.utils.unwrapObservable(allBindings.value);
$(element).select2('data', ko.utils.arrayFirst(obj.data.results, function(item) {
return item[lookupKey] === value;
}));
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).select2('destroy');
});
},
update: function(element) {
$(element).trigger('change');
}
};
i use the handler like this:
<select id="itemselector" data-bind="options: items, optionsText: 'Name', OptionsValue:'Id', select2: {}"></select>
now to make custom templates i have to pass a format function to select2 like htis
function formatSelection(item) {
return '<b>' + item.text + '</b>';
}
but i can't figure out how to do this with that binding handle. Can someone explain me how to pass the formatfunction or a string template to the binding handler, so that it will be applied to select?
Just add your option(s) into the {}
after the select2 binding declaration. For example:
<select id="itemselector" data-bind="options: items, optionsText: 'Name', optionsValue:'Id', select2: {formatResult: formatSelection}"></select>
Question back at you, the select2 binding that you are using, is a new version to me. How is the lookupKey
being used?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.