Extending dynamic and mapped data in Knockout

为君一笑 提交于 2019-12-11 09:50:09

问题


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.



来源:https://stackoverflow.com/questions/12219238/extending-dynamic-and-mapped-data-in-knockout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!