Search code examples
knockout.jsknockout-mapping-plugin

Knockout Mapping plugin not working for nested objects


I have the following JSON data fetched from the server.

var viewModel=
{ 
    InvoiceOrderID:55
    orderItem :{
        OrderItemID:32
        ProductCode:45
        Name: ZipZapper
    }   
}

I have used ko.mappingfromJS on this viewModel data. ko.mappingfromJS(viewModel,{},self)

Did the ko.applyBindings(self) to generate the bindings

How do I databind the inner nested object's ProductCode

orderItem().ProductCode does not work


Solution

  • As @tizzy pointed out, knockout mapping doesn't work this way - by default it converts properties to observables and arrays to observableArrays, but nested objects are not converted (although their inner properties are converted to observables too).

    So for your specific statement to work, your ViewModel should look like this:

    function ViewModel(data) {
        var mapping = {
            'orderItem': {
                create: function(options) {
                    return ko.observable(options.data);
                }
            }
        }
        ko.mapping.fromJS(data, mapping, this);
    }
    

    See demo.