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

Knockout mapping plugin - making all objects observable

我有以下 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" 对象仍然是一个对象并且没有被转换为可观察的(尽管 destCourse 对象中的每个 属性 都被转换为可观察的)。

如何使所有子对象的数据也转换为可观察的?最好以最通用的方式进行?

我以前遇到过这个,但我一直无法弄清楚为什么 knockout 会对子对象执行此操作。

无论如何,你只需要给映射器一点指导就可以了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>