0

我需要使用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

任何人都可以阐明这种行为的原因,以及在这种情况下更新模型的正确方法?

4

1 回答 1

0

这种情况在文档中进行了描述:要映射对象(即作为对象的 VM 的属性),您通常需要指示ko.mapping如何创建(或比较)这些对象,例如通过提供create函数:

ko.mapping.fromJS(
    {
        people: [{ firstName: 'firstName updated'}]
    }
    ,{
        'people': {
            create: function (options) {
                return new Person(options.data)
            }
        }
    }, this.data);

请参阅以下小提琴以获取解决方案:http: //jsfiddle.net/XBYhv/2/

于 2013-08-21T18:54:25.177 回答