繁体   English   中英

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

[英]Select2 in Knockout.Js with custom template

我想在敲门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,例如htis

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

但我不知道如何使用该绑定句柄执行此操作。 有人可以解释一下如何将formatfunction或字符串模板传递给绑定处理程序,以便将其应用于select吗?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM