Extending dynamic and mapped data in Knockout

2019-08-06 06:40发布

问题:

Using Knockout.JS, I'm trying to determine how to best extend objects in the view model when they will be both loaded via the mapping plugin and dynamically added. In this example, I'm adding a method addChild to the Person object.

Extending during mapping:

    var myPersonModel = function (data) {
        ko.mapping.fromJS(data, {}, this);

        this.addChild = function () {
            this.children.push(new Child());
        } .bind(this);
    }

    var mapping = {
        'people': {
            create: function (options) {
                return new myPersonModel(options.data);
            },
        }
    }

    var viewModel = ko.mapping.fromJS(data, mapping);

Extending during dynamic creation:

    function Person(id, name, children) {
        this.id = ko.observable(id);
        this.name = ko.observable(name);
        this.children = ko.observable(children);
        this.addChild = function () {
            this.Forms.push(new Child());
        } .bind(this);
    }

But it seems to me there must be an easier way to do so such that I don't need to repeat myself, and both mapped and new objects get the addChild method.

回答1:

Take a look at this answer, especially the live example on JSFiddle.

It looks like your code is close to what it needs to be.

I think you just need to fold mapping and ko.mapping.fromJS into your Person constructor.