我需要使用ko.mapping.fromJS
. 当我运行以下代码段 ( http://jsfiddle.net/XBYhv/ ) 时,一切都很好:people.firstName
已更新,新prop2
属性已添加到模型中。
var Person = function() {
this.lastName = ko.observable('lastName');
this.firstName = ko.observable('firstName');
};
var DataModel = function() {
this.people = ko.observable(new Person());
this.prop1 = ko.observable('prop1');
};
var vm = function(){
this.data = new DataModel();
this.log = function(){
console.log(this.data, this.data.people());
};
this.update = function(){
ko.mapping.fromJS(
{
people: { firstName: 'firstName updated'},
prop2: 'prop2'
}
,{}, this.data);
}
};
ko.applyBindings(new vm());
然后我想通过people
变成数组(http://jsfiddle.net/XBYhv/1/)稍微改变模型:
. . .
this.people = ko.observableArray([new Person()]);
. . .
ko.mapping.fromJS({
people: [{ firstName: 'firstName updated'}],
. . .
现在坏事发生了:people
对象被销毁并替换为[{ firstName: 'firstName updated'}]
,丢失lastName
而不是仅仅更新firstName
。
任何人都可以阐明这种行为的原因,以及在这种情况下更新模型的正确方法?