我正在尝试让淘汰赛(3.1 版)与 select2(4.0rc2 版)一起工作。
我无法让选择接受输入并进行初始选择。选择似乎是只读的。
下面是一个演示我的问题的小提琴。我在 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: { }">