Knockout.js 选择2 4.0,淘汰3.1选择不允许选择
我正在尝试让knockout(版本3.1)与select2(版本4.0rc2)一起工作 我无法获取select以接受输入并进行初始选择。select似乎是只读的 下面是一把小提琴演示我的问题。我在Chrome(版本40.0.2214.115M)上测试了这个 JavaScript:Knockout.js 选择2 4.0,淘汰3.1选择不允许选择,knockout.js,html-select,jquery-select2,jquery-select2-4,Knockout.js,Html Select,Jquery Select2,Jquery Select2 4,我正在尝试让knockout(版本3.1)与select2(版本4.0rc2)一起工作 我无法获取select以接受输入并进行初始选择。select似乎是只读的 下面是一把小提琴演示我的问题。我在Chrome(版本40.0.2214.115M)上测试了这个 JavaScript: ko.utils.setValue = function (property, newValue) { if (ko.isObservable(property)) property(newValue); else
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:
您的国家:
这里有一个更新的工作小提琴: 您遇到的主要问题是Knockout.js使用相同的
值
属性绑定所有选项,该属性为空,Select2无法正确处理。我可以通过将选项value:'id'
传递到数据绑定
属性中来解决这个问题,该属性正确地将值
属性设置为id
另一个问题是Select2不再正确地处理选择具有相同
值的选项的问题,我已经打开了一张关于该值的票据:您的小提琴没有选择所需的初始值。此外,我不想让它更新对象,而不仅仅是Id,因为该对象在我的实际程序的其他地方使用。“ko.utils.setValue”在代码中有什么作用吗?我只发现了一种情况。顺便说一句,如果您有权访问源数组并执行类似myOptions.unshift({id:undefined,text:undefined})的操作,您可以使用placehollder修复此问题@kevin brown我认为真正的问题是select2:binding不是被动的。您只需将其设置为空对象。在旧的select2 3.x+代码中,我可以编写{initSelection:function(){returnthismknockoutviewmodel.Property();}}-您似乎没有在启动时初始化值的方法。我正试图遵循自定义数据适配器的概念,但它太奇怪了,我很困惑为什么你说不应该经常使用它,因为我编写的任何商业应用程序似乎都需要它。
Your country:
<select style="width:100%;" data-bind="options: $root.availableCountries,
optionsText: 'countryName',
value: selectedCountry,
select2: { }">