Knockout映射插件 - 使所有对象都可观察

时间:2018-05-03 12:26:07

标签: knockout.js knockout-mapping-plugin

我有以下Knockout视图模型:

var myViewModel = {
    courseData: ko.observable(null);
};

然后我从服务器收到以下数据:

var data = {
  "courses": [
    {
      "srcCourses": [ { "code": "001", "name": "Course 1"}, { "code": "002", "name": "Course 2"} ],
      "destCourse": { "code": "003", "name": "Course 3"}
    },
    {
      "srcCourse": [ { "code": "004", "name": "Course 4"}, { "code": "005", "name": "Course 5"} ],
      "destCourse": { "code": "006", "name": "Course 6"}
    }
  ]
}

我通过Knockout映射插件运行到我的视图模型中,如下所示:

this.courseData(ko.mapping.fromJS(data));

这基本上让我看到了以下视图模型对象层次结构:

{
  KnockoutObservable(this.courseData): {
    KnockoutObservableArray(Courses): [
      {
        KnockoutObservableArray(srcCourses): [ ... ],
        destCourse: { KnockoutObservable(code), KnockoutObservable(name) }
      },
      {
        ...
      }
    ]
  }
}

问题是“destCourse”对象仍然是一个对象,并且不会转换为observable(尽管destCourse对象中的每个属性都转换为observable)。

如何将所有子对象的数据转换为可观察的?理想情况下,以最通用的方式?

1 个答案:

答案 0 :(得分:2)

我之前遇到过这种情况,我从来没有弄清楚为什么淘汰赛会对儿童物品做这件事。

无论如何,您只需要给映射器一些指导as described in the docs

var coursesMapping = {
  "destCourse":{
    create:function(options){
      return ko.observable(ko.mapping.fromJS(options.data));
    }
  }
}

var mapped = ko.mapping.fromJS(data, coursesMapping);

这是一个片段:

var data = {
  "courses": [
    {
      "srcCourses": [ { "code": "001", "name": "Course 1"}, { "code": "002", "name": "Course 2"} ],
      "destCourse": { "code": "003", "name": "Course 3"}
    },
    {
      "srcCourse": [ { "code": "004", "name": "Course 4"}, { "code": "005", "name": "Course 5"} ],
      "destCourse": { "code": "006", "name": "Course 6"}
    }
  ]
}

var coursesMapping = {
  "destCourse":{
    create:function(options){
      return ko.observable(ko.mapping.fromJS(options.data));
    }
  }
}

var mapped = ko.mapping.fromJS(data,coursesMapping);

console.log(mapped.courses()[0].destCourse().name()); // "Course 3"
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script>