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

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

问题描述

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

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

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

在这个小提琴示例中,我试图将孩子正确映射到他们的自定义创建.预期的结果是每个 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:

  • 亚当·斯密
  • 鲍勃 5 岁
  • 克里斯 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);

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

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.

有没有办法使用 Knockout Mapping 自定义创建父对象和子对象?

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);

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

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