使用自定义模板在Knockout.Js中选择t2

Select2 in Knockout.Js with custom template

本文关键字:Js 选择 t2 Knockout 自定义      更新时间:2023-09-26

我想在knockout.js中使用select2

我有一个绑定处理程序。

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');
    }
};

我这样使用处理程序:

 <select id="itemselector" data-bind="options: items, optionsText: 'Name', OptionsValue:'Id', select2: {}"></select>    

现在要创建自定义模板,我必须向select2传递一个格式函数,如hthis

 function formatSelection(item) {
          return '<b>' + item.text + '</b>';
        }

,但我不知道如何做到这一点与绑定句柄。有人能告诉我如何将formatfunction或字符串模板传递给绑定处理程序,以便将其应用于选择吗?

只需在select2绑定声明之后将您的选项添加到{}中。例如:

 <select id="itemselector" data-bind="options: items, optionsText: 'Name', optionsValue:'Id', select2: {formatResult: formatSelection}"></select>

回到你的问题,你正在使用的select2绑定对我来说是一个新版本。lookupKey是如何使用的?