剔除映射-使用嵌套对象自定义创建 [英] Knockout Mapping - Customize Create with Nested Objects

查看:78
本文介绍了剔除映射-使用嵌套对象自定义创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了KnockoutJS的映射插件的问题,我需要执行以下操作:

I'm running into an issue with KnockoutJS's mapping plugin where I need to do the following:

  1. 自定义对象的映射创建
  2. 自定义#1中嵌套对象数组的映射创建.

在这个小提琴示例中,我试图将 children 正确映射到他们的自定义创建.预期结果是每个 children 都具有添加的 description 属性.从小提琴中,结果应显示为:

In this fiddle example I am trying have the children properly mapped to their custom creation. The expected result is that each of the children have the added description property. From the fiddle, the result should read:

  • 亚当·史密斯
  • 鲍勃(Bob)5岁
  • Chris 7岁

在这个小提琴示例中,我可以证明预期的行为.注意,在这段代码中,我必须有两个数据集,第一个数据集有一个空的子对象数组.以下代码行将导致子对象的自定义创建:

I can demonstrate the expected behaviour in this this fiddle example. Notice that in this code I must have two data sets, with the first having an empty array of children objects. The following line of code will cause the customized creation of child objects:

ko.mapping.fromJS(additionalData, parentMapping, viewModel);

不幸的是,这需要同时拥有空的初始子级和映射两次.这是不可接受的,因为现实中的代码具有更深的层次结构.

Unfortunately, this requires both having empty initial children and mapping twice. This is not acceptable as the code in reality has a much deeper hierarchy.

除上述内容外,我还尝试在parentMapping中添加以下代码:

In addition to the above, I've tried adding the following code in the parentMapping:

var mapping = { 'ignore': ["children"] };
var innerModel = ko.mapping.fromJS(options.data, mapping);
//for brevity
innerModel.children = ko.mapping.fromJS(options.data.children, childMapping);

这具有在初始映射上映射 children 对象的作用.但是,所有 children 属性的后续映射都将被忽略.

This has the effect of mapping the children objects on the initial mapping. However, all subsequent mappings the children property is ignored.

是否可以通过敲除映射自定义创建父对象和子对象的方法?

Is there a way to customize the creation of both a parent and child object with Knockout Mapping?

谢谢.

推荐答案

http://jsfiddle.net/5cfa3 /23/

var viewModel = {};

var data = {
  id: "1",
  firstName: 'Adam',
  lastName: "Smith",
  children: [ {id: "2", name: "Bob", age: 5}, {id: "3", name: "Chris", age: 7 }]
};

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

var mapping = {
  create:function(options){
    var parent = new Parent(options.data);
    parent.fullName = ko.computed(function(){
        return parent.firstName() + " " + parent.lastName();
    });
    return parent;
  },
  'children': {
     create: function(options) {
         options.data.description = ko.computed(function(){
             return options.data.name + " is " + options.data.age + " years old ";
         });
         return ko.mapping.fromJS(options.data);         
     }
   }
};

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

ko.applyBindings(viewModel);

这篇关于剔除映射-使用嵌套对象自定义创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆