Select2 4.0和Knockout 3.1选择不允许选择

时间:2015-03-16 21:50:14

标签: knockout.js html-select jquery-select2 jquery-select2-4

我试图让淘汰赛(版本3.1)与select2(版本4.0rc2)一起使用。

我无法让select接受输入并进行初始选择。选择似乎是只读的。

以下是展示我问题的小提琴。我在Chrome上测试了这个版本(版本40.0.2214.115 m)。

http://jsfiddle.net/R8UF5/402/

JavaScript的:

ko.utils.setValue = function (property, newValue) { if (ko.isObservable(property)) property(newValue); else property = newValue; };

ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor) {
    var obj = valueAccessor(),
        allBindings = allBindingsAccessor(),
        lookupKey = allBindings.lookupKey;

    $(element).select2(obj);

    ko.utils.registerEventHandler(element, "select2-selected", function (data) {
        if ('selectedValue' in allBindingsAccessor()) {
            ko.utils.setValue(allBindingsAccessor().selectedValue, data.choice);
        }
    });

    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
        $(element).select2('destroy');
    });
},
update: function (element, valueAccessor, allBindingsAccessor) {
    var options = allBindingsAccessor().select2Options || {};

    for (var property in options) {
        $(element).select2(property, ko.utils.unwrapObservable(options[property]));
    }

    $(element).trigger('change');
}
};

// Constructor for an object with two properties
var Country = function(name, population, price) {
    this.countryName = name;
    this.countryPopulation = population;
    this.price = price;
    this.id = price;
    this.text = name;
};

var countries = [ new Country("UK", 65000000,1), new Country("USA", 320000000,2), new Country("Sweden", 29000000,3)];
var viewModel = {
    availableCountries : ko.observableArray(countries),
    selectedCountry : ko.observable(countries[1])
};
ko.applyBindings(viewModel);

HTML:     

Your country:
<select style="width:100%;" data-bind="options: $root.availableCountries,
                   optionsText: 'countryName',
                   value: selectedCountry, 
                   select2: {  }">

1 个答案:

答案 0 :(得分:6)

这是一个更新的工作小提琴:http://jsfiddle.net/R8UF5/404/

您遇到的主要问题是Knockout.js使用相同的value属性绑定所有选项,该属性为空,而Select2无法正确处理。我能够通过将optionsValue: 'id'传递到data-bind属性来解决此问题,该属性正确地将value属性设置为id。

另一个问题是,Select2不再正确处理选择具有相同value的选项,我已经开了一张关于https://github.com/select2/select2/issues/3163的票据

相关问题