我正在尝试通过单个绑定处理程序访问多个值,如果在 valuesAccessor 绑定对象内发生 observableArray 更改,则绑定处理程序更新不会触发。
ko.bindingHandlers.chosen = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
console.log("INIT");
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = ko.unwrap(valueAccessor());
ko.utils.arrayForEach(value,function(binding){
var value = ko.unwrap(binding);
});
console.log("IT WORKS!");
}
};
<select data-bind="
options: Options,
chosen: {options: Options}
"></select>
演示:(也在 jsFiddle 上):
ko.bindingHandlers.chosen = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
console.log("INIT");
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = ko.unwrap(valueAccessor());
ko.utils.arrayForEach(value,function(binding){
var value = ko.unwrap(binding);
});
console.log("IT WORKS!");
}
};
function Model() {
this.Options = ko.observableArray(opt1);
this.Reload = function () {
if (!this.index) {
this.Options(opt2);
this.index = 1;
} else {
this.Options(opt1);
this.index = 0;
}
this.Options.valueHasMutated();
};
this.index = 0;
}
var opt1 = [{
Text: "1",
Value: "1"
}, {
Text: "2",
Value: "2"
}, ];
var opt2 = [{
Text: "3",
Value: "3"
}, {
Text: "4",
Value: "4"
}, ];
ko.applyBindings(new Model());
<select data-bind="
options: Options,
value: Selection,
optionsText: 'Text',
optionsValue: 'Value',
chosen: {options: Options}
"></select>
<input type="button" data-bind="click: Reload" value="reload" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>