简体   繁体   English

在淘汰赛中扩展动态数据和映射数据

[英]Extending dynamic and mapped data in Knockout

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. 使用Knockout.JS,我试图确定如何最好地在视图模型中扩展对象,这些对象既可以通过映射插件加载,也可以动态添加。 In this example, I'm adding a method addChild to the Person object. 在此示例中,我向Person对象添加了方法addChild。

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. 但是在我看来,必须有一种更简单的方法来执行此操作,这样我就不必重复自己了,映射的对象和新对象都可以使用addChild方法。

Take a look at this answer , especially the live example on JSFiddle . 看一下这个答案 ,尤其是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. 我认为您只需要将mappingko.mapping.fromJS折叠到您的Person构造函数中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM