Knockout mapping complex object

烈酒焚心 提交于 2020-01-06 15:16:34

问题


For example, we have complex object:

var complex = {a: 1, b: 2, c: {c1: 1, c2: 2}};

We want it to make observable:

var observableComplex = ko.mapping.fromJS(complex);

Question: why we get c variable not observable? I was seen somewher in manuals, that this is done by design and I want to know why?

a - observable,
b - observable
c - object:
  c1 - observable
  c2 - observable

回答1:


There is no object for 'c' that can be mapped...if you want it to be observed, you need to create a custom mapping for it and define your object.

ie

var Complex = function (data) {
    var self = this;
    self.c = ko.mapping.fromJS(data.c);
}

var CustomMapping = {
    create: function(options) {
        return new Complex(options.data);
    }
}

var observableComplex = ko.mapping.fromJS(complex, CustomMapping);

In short, this creates a new Complex object then digs in and maps the data for 'c' as observableComplex is created. For my custom objects, I have quite a few situations like this for dealing with nested objects.



来源:https://stackoverflow.com/questions/20427555/knockout-mapping-complex-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!