爲什麼初始值selectPicker不適用於Knockout版本3.4?用Knockout 3.0工作。淘汰賽3.4 select bootstrap selectpicker
<select data-bind="selectPicker: teamID, items: teamItems, optionsText: 'text', optionsValue : 'id'"></select>
<div>Selected Value(s)
<div data-bind="text: teamID"></div>
</div>
<button data-bind="click: setActive">
Set active
</button>
<button data-bind="click: addStef">
Add Stefan
</button>
function ViewModel() {
var self = this;
this.teamItems = ko.observableArray([
{
text: 'Chris',
id: 1
},
{
text: 'Peter',
id: 2
},
{
text: 'John',
id: 3
}]);
//init value not working
this.teamID = ko.observable(3);
////
this.setActive = function() {
this.teamID(3);
}
this.addStef = function() {
this.teamItems.push({ text: "Stef", id: 4 })
}
}
ko.bindingHandlers.selectPicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
if ($(element).is('select')) {
$(element).addClass('selectpicker').selectpicker();
if (ko.isObservable(valueAccessor())) {
if ($(element).prop('multiple') && $.isArray(ko.utils.unwrapObservable(valueAccessor()))) {
ko.bindingHandlers.selectedOptions.init(element, valueAccessor, allBindingsAccessor);
} else {
ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);
}
}
}
},
update: function (element, valueAccessor, allBindingsAccessor) {
if ($(element).is('select')) {
var options = allBindingsAccessor().items;
if (typeof options !== 'undefined' && options !== null) {
var isDisabled = allBindingsAccessor().disable || false;
if (ko.utils.unwrapObservable(options).length > 0) {
// call the default Knockout options binding
ko.bindingHandlers.options.update(element, options, allBindingsAccessor);
}
if (isDisabled) {
// the dropdown is disabled and we need to reset it to its first option
$(element).selectpicker('val', $(element).children('option:first').val());
}
$(element).prop('disabled', isDisabled);
}
if (ko.isObservable(valueAccessor())) {
var value = ko.utils.unwrapObservable(valueAccessor());
if ($(element).prop('multiple') && $.isArray(value)) {
ko.bindingHandlers.selectedOptions.update(element, valueAccessor);
} else {
// call the default Knockout value binding
ko.bindingHandlers.value.update(element, valueAccessor);
}
}
}
}
};
ko.applyBindings(new ViewModel());
問題是與線 this.teamID = ko.observable(3);
所選值始終等於數組中的第一個元素。
它似乎發生在'ko.bindingHandlers.options.update(element,options,allBindingsAccessor);'但我不知道爲什麼。 –
http://jsfiddle.net/un2g5rd0/約翰應該選擇 –