0
votes

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
Yes this is by design. And probably you should ask the authors about the reason behind this decision...nemesv
@nemesv Not to be argumentative, but ...if you're not the author, how is it that you know this is by design?id.ot

1 Answers

0
votes

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.