问题
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