Question

I'm trying to map JSON data to a child object, I can get it to work using the root object:

var data = {transfer: {"VisitTransferId":"a46bb9ce-9feb-410b-b643-d917560bb6e5","FromVisit":"16*15997*2*2","ToVisit":"10*1*9*9*9"}}; ko.mapping.fromJS(data, {}, visitDetailsVm);

like in this JSFiddle here, but I'd like to know why it doesn't work when specifying the child object when doing the mapping (the data is not the same between these two):

var data = {"VisitTransferId":"a46bb9ce-9feb-410b-b643-d917560bb6e5","FromVisit":"16*15997*2*2","ToVisit":"10*1*9*9*9"}; ko.mapping.fromJS(data, {}, visitDetailsVm.transfer);

like here

Was it helpful?

Solution

When you run mapping and provide the variable to receive the data, you're actually setting the value of a variable...not filling the observable. So you're overriding the observable entirely.

Check out http://jsfiddle.net/BWgwt/3/

        var visitDetailsVm = new VisitDetails();
        visitDetailsVm.transfer(ko.mapping.fromJS(data));

        var mappedAmas = ko.utils.arrayMap(amadata, function(ama) {
            return ko.mapping.fromJS(ama);
        });
        visitDetailsVm.amas(mappedAmas);

With the observable array, you'd actually want to map each of the instances in your data array then fill your observable array with the mapped results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top