我的解决方案是只有一个 observableArray,而不是两个。
将从您的 2 个服务调用接收到的数据合并到一个对象列表中。
例如,
var orgChart = getDataFromFirstServiceCall();
var selectedDepartments = getDataFromSecondServiceCall();
var vm = {
departments = ko.observableArray(),
}
function Department( id , name ) {
this.id = id;
this.name = name;
this.selected = selectedDepartments.indexOf(id) !== -1;
}
for( var i = 0; i < orgChart.length; i++ ) {
var dept = orgChart[i];
vm.departments.push( new Department( dept.id , dept.name );
}
ko.applyBindings( vm );
现在在您的 HTML 中,您可以这样做:
<div data-bind="foreach: departments">
<div>
<input type="checkbox" data-bind="checked: selected }" />
<span data-bind="text: name"/>
</div>
</div>
编辑:
要将数据发送回服务器,只需遍历部门数组并获取selected
标志设置为的那些true
var departments = vm.departments(),
selected = [];
for( var i = 0; i < departments.length; i++ ) {
var dept = departments[i];
if( dept.selected ) selected.push(dept);
}
瞧!
或者,如果您想为数据库节省带宽和/或删除/插入语句,您可以创建selected
一个 observable,订阅它的更改,然后将其单独保存到服务器。
function Department( id , name ) {
var self = this;
self.id = id;
self.name = name;
self.selected = ko.observable( selectedDepartments.indexOf(id) !== -1 );
self.selected.subscribe(function(newValue) {
// save newValue to the database
// perform an ajax POST, sending self.id and newValue
});
}