【问题标题】:Select2 in Knockout.Js with custom template带有自定义模板的 Knockout.Js 中的 Select2
【发布时间】:2014-08-01 18:51:16
【问题描述】:

我想在 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>    

现在要制作自定义模板,我必须像 htis 一样将格式函数传递给 select2

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

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

【问题讨论】:

  • 我想你忘了包括你使用处理程序的位(你说“像这样:”没有任何东西)。
  • 是的,对不起,我添加了它

标签: javascript knockout.js jquery-select2


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多