KO 中的绑定是双向的;如果您更新视图模型,UI 也会更新。如果您更新绑定的控件,则视图模型会更新。
您还可以创建计算属性,只要任何引用的 observables 更新,它就会更新。
function ViewModel(data) {
data = data || {};
this.checkboxes = ko.observableArray(
ko.utils.arrayMap(data.checkboxes, function (title) {
return new CheckboxModel(title);
})
);
this.checkedCheckboxes = ko.computed(function () {
return ko.utils.arrayFilter(this.checkboxes(), function (cb) {
return cb.checked();
});
}, this);
}
function CheckboxModel(title) {
this.title = ko.observable(title);
this.checked = ko.observable(false);
this.number = ko.observable(1);
}
$(function() {
ko.applyBindings(new ViewModel({
checkboxes: [ 'Champion', 'Reserve champion',
'1st', '2nd', '3rd', '4th', '5th', '6th',
'7th', '8th', '9th', '10th', 'Other']
}));
});
<div data-bind="foreach: checkboxes" id="cblist">
<label data-bind="visible: checked">
<input type="number" data-bind="value: number"/>
<span data-bind="text: title"></span>
</label>
<label data-bind="visible: !checked()">
<input type="checkbox" data-bind="checked: checked"/>
<span data-bind="text: title"></span>
</label>
<br/>
</div>
http://jsfiddle.net/MizardX/zHTRP/