KO中的绑定是双向的;如果更新视图模型,则会更新UI . 如果更新绑定控件,则视图模型会更新 .
您还可以创建计算属性,只要任何引用的observable更新,它就会更新 .
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']
}));
});