Knockout mapping complex object

2019-09-02 03:54发布

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条回答
戒情不戒烟
2楼-- · 2019-09-02 04:15

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.

查看更多
登录 后发表回答