sou*_*mer 3 html-select knockout.js jquery-select2 jquery-select2-4
我试图让淘汰赛(版本3.1)与select2(版本4.0rc2)一起使用.
我无法让select接受输入并进行初始选择.选择似乎是只读的.
下面是一个表明我的问题的小提琴.我在Chrome上测试了这个(版本40.0.2214.115米).
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);
Run Code Online (Sandbox Code Playgroud)
HTML:
Your country:
<select style="width:100%;" data-bind="options: $root.availableCountries,
optionsText: 'countryName',
value: selectedCountry,
select2: { }">
Run Code Online (Sandbox Code Playgroud)
这是一个更新的工作小提琴:http://jsfiddle.net/R8UF5/404/
您遇到的主要问题是Knockout.js使用相同的value属性绑定所有选项,该属性为空,并且Select2无法正确处理它.我能够通过传入属性来解决这个问题,optionsValue: 'id'该data-bind属性正确地将value属性设置为id.
另一个问题是Select2不再正确处理选择相同的选项value,我已经开了一张票:https://github.com/select2/select2/issues/3163