看看这个小例子。
<select data-bind="options: Days, optionsText: 'title'"></select>
<input type="button" value="update" data-bind="click: update" />
<script type="text/javascript">
var Days = {'Days': [{"id":1,"title":"Monday"},{"id":2,"title":"Tuesday"},{"id":3,"title":"Wensday"}]};
var DaysUpdate = {'Days': [{"id":3,"title":"Wednesday"},{"id":4,"title":"Thursday"},{"id":5,"title":"Friday"}]};
var mapping = {
'Days': {
key: function(data) {
return ko.utils.unwrapObservable(data.id);
}
}}
var viewModel = {
Days: ko.observableArray(),
update: function() {
ko.mapping.fromJS(DaysUpdate, mapping, viewModel);
}
}
ko.mapping.fromJS(Days, mapping, viewModel);
ko.applyBindings(viewModel);
</script>
在此示例中,数据被部分映射。首先来自 Days 对象,然后(通过单击更新按钮)来自 DaysUpdate 对象。第二次更新从数组中删除“Monday”和“Tuesday”对象。我如何让那些留下来?
PS。感谢 Mark Robinson 提供了结构更好的示例。